FileUploadInterceptor interceptor notes, interceptor
When the request form contains a file, the FileUploadInterception interceptor automatically applies to this file.
Form: <s: form namespace = "/xxx" action = "yyy" method = "post" enctype = "multipart/form-data"> <s: file name = "file" label = "YourFile"> </s: file> <s: submit> </s: form>
We can add three attributes to the action to receive files, file types, and file names. The Demo is as follows:
* 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; * } * }
Of course, you can set parameters to restrict the size and type of the uploaded file, or use the File suffix to restrict the type of the uploaded file.
- MaximumSize: indicates the maximum size of uploaded files. The unit is byte. The default value is 2 MB.
- AllowedTypes: indicates the types of files that can be uploaded. Each type is separated by commas (,) (ie: text/html, image/jpg ). If this parameter is not specified, files of any type can be accepted.
- AllowedExtensions: allows you to upload files ending with these suffixes. Each suffix is separated by commas (,) (ie:. html,. jpg ). If this parameter is not specified, files of any type can be accepted.
Ie: <interceptor-ref name = "defaultStack"> <! -- Specify the size of the uploaded file --> <param name = "fileUpload. maximumSize"> 6000 </param> <! -- Specify the type of the uploaded file with the suffix --> <param name = "fileUpload. allowedExtensions"> .text,.jpg, .png </param> <! -- Specify the type of the uploaded file as the file type --> <param name = "fileUpload. allowedTypes"> image/png </param> </interceptor-ref>
If the uploaded file does not meet the specified requirements, the error message is returned. These error messages are based on i18n and stored in the struts-messages.properties configuration file. We can also rewrite these error messages using keywords:
* <Li> struts. messages. error. uploading-a general error that occurs when the file cocould 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>