JSF 2.2: File Upload

#JSF 2.2: File Upload#

Before 2.2, you have to use Richfaces, Primefaces like JSF components to provide file upload feature.

Or you must write a custom file upload component yourself.

Luckily this long waiting feature was finally added in JSF 2.2.

<pre> &lt;h:form enctype="multipart/form-data"> &lt;h:inputFile id="file" value="#{fileUploadBean.file}" /> &lt;h:commandButton value="Upload" action="#{fileUploadBean.upload()}"/> &lt;/h:form> </pre>

A new inputFile component is provided for file upload purpose. The usage is simple. Like other input components, put it into a h:form, and change the enctype attribute to multipart/form-data, it is a must for file upload.

<pre> @Model public class FileUploadBean { @Inject Logger log; private Part file; public void upload(){ log.info("call upload..."); log.log(Level.INFO, "content-type:{0}", file.getContentType()); log.log(Level.INFO, "filename:{0}", file.getName()); log.log(Level.INFO, "submitted filename:{0}", file.getSubmittedFileName()); log.log(Level.INFO, "size:{0}", file.getSize()); try { byte[] results=new byte[(int)file.getSize()]; InputStream in=file.getInputStream(); in.read(results); } catch (IOException ex) { log.log(Level.SEVERE, " ex @{0}", ex); } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Uploaded!")); } public Part getFile() { return file; } public void setFile(Part file) { this.file = file; } } </pre>

In the backend bean, use a standard Servlet 3 Part as converted type to warp the uploaded file info.

You can easily get the uploaded file info from Part API.

NOTE: The getName method will return the client id, and getSubmittedFileName returns the original file name.

Uploaded file content can be read through the getInputStream method.

转载于:https://my.oschina.net/hantsy/blog/145498

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值