How to get browsed file path in java

こ雲淡風輕ζ 提交于 2019-12-08 13:56:01

问题


I want to get a browsed files path. i tried like it

Object objUploadEvent = ctx.getTriggerEvent();
        if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
            upEvent = (UploadEvent) objUploadEvent;
        }
        if (upEvent != null) {
            Media media = upEvent.getMedia();
            File file=new File(media.getName());
            this.path = file.getAbsolutePath();
        }

But getAbsolutePath is giving path from eclipse. say if my file is in c://doc/abc then it should give path as c://doc/abc/myfile.txt

Thanks


回答1:


If you print out the media.getName() to your log, you will most probably see that it is just the file name, without path: myfile.txt

That's because it is up to the browser how much information about a file they send along with the uploaded bytes. And most browsers just give you the name without path. Try opera, there you should get the complete filepath.




回答2:


If the file is on the client (where the browser is), this is probably not possible with the usual file uploader. This question has some alternatives that solve the exact same problem that you are facing

If the file is on your server, try file.getCanonicalPath(). This should give you the entire path.

Also see: What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

By the way, you can get the directory from which your program was started, the eclipse directory, using System.getProperty("user.dir")). However I don't recommend using this if all you need is the path to a file.




回答3:


If I understand correctly, you want the location of the source file on the client as opposed to the location of the file on the server?

This is not possible for security reasons, sorry.

You'll find plenty of discussion about this on StackOverflow and elsewhere (sometimes in reference to the 'fakepath' symptom of some browser's implementation of this security feature.

Without going into too much detail, the reasoning for this security feature is quite simple; no website should need to (read: be able to) find out anything about a user's file system. As such, when a file is uploaded to a server only the file data should be sent.

Technically, it was possible in some older browsers (eg: IE6 I believe) but is a pretty ubiquitous security feature at this point and you would be ill fated to depend on this information.



来源:https://stackoverflow.com/questions/14332055/how-to-get-browsed-file-path-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!