當請求表單中包含一個文件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>