How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

冷暖自知 提交于 2019-11-26 04:52:53
BalusC

JSF won't save the file in any predefined location. It will basically just offer you the uploaded file in flavor of a javax.servlet.http.Part instance which is behind the scenes temporarily stored in server's memory and/or temporary disk storage location which you shouldn't worry about.

In order to save it to the desired location, you need to get the content by Part#getInputStream() and then copy it to the Path representing the location. You can do this in an (ajax) action (listener) method the usual way. Here's an example which does it with an ajax listener during the HTML DOM change event:

<h:form enctype="multipart/form-data">
    <h:inputFile value="#{bean.file}">
        <f:ajax listener="#{bean.save}" />
    </h:inputFile>
</h:form>
private Part file; // +getter+setter

public void save() {
    try (InputStream input = file.getInputStream()) {
        Files.copy(input, new File(uploads, filename).toPath());
    }
    catch (IOException e) {
        // Show faces message?
    }
}

The uploads folder and the filename is fully under your control. E.g. "/path/to/uploads" and Part#getSubmittedFileName() respectively. Keep in mind that any existing file would be overwritten, you might want to use File#createTempFile() to autogenerate a filename.

Do not use Part#write() as some prople may suggest. It will basically rename the file in the temporary storage location as identified by @MultipartConfig(location). Also do not use ExternalContext#getRealPath() in order to save the uploaded file in deploy folder. The file will get lost when the WAR is redeployed for the simple reason that the file is not contained in the original WAR. Always save it on an absolute path outside the deploy folder.

For a live demo, check the last item of <o:graphicImage> demo on OmniFaces showcase.

See also:

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