简体   繁体   中英

upload file in jsf 2.2

Using my company's chosen cloud storage api and just starting out with JSF 2.2. Trying to build a simple image upload web app and it works when I run locally using Eclipse.

Here's the code: .xhtml page

<h:form id="form" enctype="multipart/form-data" prependId="false">
Select id Photo: <h:inputFile id="file" value="#{customerEntity.uploadedFile}"/> 
<h:commandButton value="Query Cloud" 
action="#{customerEntity.addActionController}"/> 
</h:form>

customerEntity.java code:

private Part uploadedFile;
private String fileURI;

On local machine, code to extract file name from Part object uploadedFile produces correct file locator (eg. c:\\pictures\\mypix.jpg) for local access on my machine.

However, when I load into tomcat 7 running in a cloud vm, the application fails with a FileNotFound in the 'try' block:

 File source = new File(this.fileURI);
 try {
 cloud.upload(new FileInputStream(source), source.length());

My debug statements show it's using the file locator from my local pc which clearly doesn't exist on the server. I can't figure out how to get the local file data streamed to the code running on the server.

As a slight jsf newbie, I'm sure it's something obvious, but can't figure it out or resolve via some of the other posts I've seen.

Any guidance would be greatly appreciated!

You're making a rather major conceptual mistake. You should not be interested in the client-specified path/name of the uploaded file. Instead, you should be interested in the content of the uploaded file. And well due to 2 main reasons:

  1. The path to the file will be totally absent when you're using a webbrowser which doesn't expose a security bug that the full client side path is included in the name of the uploaded file (ie any browser other than Internet Explorer).

  2. Using new File() on the client-specified path/name would only work if both the webbrowser (which is been used to send the file) and the webserver (which is been used to retrieve the file) runs at physically the same machine, because they have then access to exactly the same local disk file system structure. This doesn't occur in real world.

In order to save the content of the uploaded file in the desired location, do so:

uploadedFile.write("/path/to/uploads/somefilename.ext");

Note: you need to make sure that the somefilename.ext part is unique in its folder. You can if necessary make use of File#createTempFile() to autogenerate an unique filename in the given folder based on filename prefix and suffix.

File file = File.createTempFile("somefilename-", ".ext", new File("/path/to/uploads"));
uploadedFile.write(file.getAbsolutePath());

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM