FileUploadInterceptor拦截器的笔记

时间:2023-03-09 15:50:13
FileUploadInterceptor拦截器的笔记

当请求表单中包含一个文件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;
* }
* }

 当然,可以设置参数来限制上传文件的大小、文件的类型,也可以通过文件的后缀名来限制上传文件的类型。

  • maximumSize:表示上传文件大小的上限,单位是byte。默认2MB。
  • allowedTypes:表示允许上传文件的类型,每个类型之间用逗号分隔开(ie: text/html, image/jpg)。如果没有指定这个参数,则可以接受任何类型的文件。
  • allowedExtensions:表示允许上传以这些后缀结尾的文件,每个后缀之间用逗号分隔开(ie: .html, .jpg)。如果没有指定这个参数,则可以接受任何类型的文件。
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>