标签:
当请求表单中包含一个文件file,FileUploadInterception拦截器会自动应用于这个文件。
表单:
<s:form namespace="/xxx" action="yyy" method="post" enctype="multipart/form-data">
<s:file name="file" label="YourFile"></s:file>
<s:submit></s:submit>
</s:form>
我们可以在action中添加三个属性来接收文件、文件的类型和文件名,Demo如下:
* package com.example; * * import java.io.File; * import com.opensymphony.xwork2.ActionSupport; * * public UploadAction extends ActionSupport { * private File file; * private String contentType; * private String filename; * * public void setUpload(File file) { * this.file = file; * } * * public void setUploadContentType(String contentType) { * this.contentType = contentType; * } * * public void setUploadFileName(String filename) { * this.filename = filename; * } * * public String execute() { * //... * return SUCCESS; * } * }
当然,可以设置参数来限制上传文件的大小、文件的类型,也可以通过文件的后缀名来限制上传文件的类型。
ie:
<interceptor-ref name="defaultStack">
<!-- 指定上传文件的大小 -->
<param name="fileUpload.maximumSize">6000</param>
<!-- 以后缀名指定上传文件的类型 -->
<param name="fileUpload.allowedExtensions">.text,.jpg,.png</param>
<!-- 以文件类型指定上传文件的类型 -->
<param name="fileUpload.allowedTypes">image/png</param>
</interceptor-ref>
如果上传的文件不符合指定的要求,会回显错误信息。这些错误信息基于i18n,存放在struts-messages.properties配置文件中。我们也可以通过关键字来重写这些错误信息:
* <li>struts.messages.error.uploading - a general error that occurs when the file could not be uploaded</li>
* <p/>
* <li>struts.messages.error.file.too.large - occurs when the uploaded file is too large</li>
* <p/>
* <li>struts.messages.error.content.type.not.allowed - occurs when the uploaded file does not match the expected
* content types specified</li>
* <p/>
* <li>struts.messages.error.file.extension.not.allowed - occurs when the uploaded file does not match the expected
* file extensions specified</li>
标签:
原文地址:http://www.cnblogs.com/ming-zi/p/5799097.html