How to get JSF to upload file with Apache Commons FileUpload

╄→гoц情女王★ 提交于 2019-12-05 10:21:47
BalusC

So when I try to print the content type above, it showed application/x-www-form-urlencoded.

The <p:commandButton> sends by default an ajax request of level 1 XMLHttpRequest. This does not support multipart/form-data. Only level 2 XMLHttpRequest supports it, but it's only supported in the newest browsers (those also supporting HTML5) and not implemented in JSF JS API nor in PrimeFaces JS API.


If I put ajax="false" to my p:commandButton, then the submit() method is not even invoked

This way however a fullworthy multipart/form-data will be sent. That the submit method is not invoked is just because JSF prior to version 2.2 does not support multipart/form-data requests out the box. JSF collects the submitted data by default using request.getParameter() and getParameterMap() on the underlying HTTP servlet request. However, this will return null when an encoding other than application/x-www-form-urlencoded is been used. As JSF determines the to-be-invoked action method based on submitted data, it won't be able to locate and invoke it when the data is null.

In theory, if you create a Filter which uses Apache Commons FileUpload or the new Servlet 3.0 request.getPart()/getParts() methods to extract the data from the multipart/form-data request and wraps the current HTTP servlet request with a custom implementation which overrides the getParameter() calls wherein a mapping of the extracted data is been supplied, then JSF will be able to do the needed job based on results of getParameter() calls. You can find a concrete example utilizing the Servlet 3.0 API in this article and the same example which is slightly changed to utilize Apache Commons FileUpload in this answer.

The upcoming JSF 2.2 will have a new <h:inputFile> component which is bindable to a Servlet 3.0 Part property.

<h:form enctype="multipart/form-data">
    <h:inputFile value="#{bean.file}" />
    <h:commandButton value="submit" action="#{bean.submit}" />
</h:form>

with

private Part file;

JSF 2.2 final release is scheduled for late end of Q1, but is currently available as a snapshot release.

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