Preface
When developing web applications, we must provide users with uploading functions, such as uploading an image as an avatar. In order to upload files, we must set the method of the form to POST and the enctype to multipart/form-data . Only in this case will the browser send the binary data of the user's selected file to the server. This article will give a detailed summary of the upload function in the Struts2 framework. I won’t say much below, let’s take a look at the detailed introduction together.
Struts2 file upload
Struts2 does not provide its own request parser, that is, Struts2 will not handle multipart/form-data requests by itself. It needs to call other upload frameworks to parse binary request data, but Struts2 further encapsulates the original upload parser, further simplifying file upload.
In the default.properties configuration file of Struts2, you can see the configuration code like this:
### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data# struts.multipart.parser=cos# struts.multipart.parser=pell# struts.multipart.parser=jakarta-streamstruts.multipart.parser=jakarta# uses javax.servlet.context.tempdir by defaulttruts.multipart.saveDir=struts.multipart.maxSize=2097152
The above code is mainly used to configure the upload parser when uploading files in Struts2. The encapsulation of Struts2 isolates the difference between the underlying file upload components. As long as the resolver is used for uploading this configuration file, developers can easily switch between different file upload frameworks.
Struts2 uses jakarta upload parser by default, of course, if you don't like it, you can also switch to something else. The following is a simple file upload function based on Struts2 through code.
Implement the action of file upload
Front Desk Page:
<form action="upload" method="post" enctype="multipart/form-data"> Title:<input type="text" name="title"><br> File:<input type="file" name="upload"><br> <input type="submit" value="submit"></form>
Action class:
public class UploadAction extends ActionSupport{ private String title; private File upload; private String uploadContentType; private String uploadFileName; private String savePath; public void setSavePath(String value) { this.savePath = value; } private String getSavePath() { String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/" + savePath); return realPath; } public void setTitle(String value) { this.title = value; } public String getTitle() { return title; } public void setUpload(File value) { this.upload = value; } public File getUpload() { return upload; } public void setUploadContentType(String value) { this.uploadContentType = value; } public String getFileContentType() { return uploadContentType; } public void setUploadFileName(String value) { this.uploadFileName = value; } public String getUploadFileName() { return uploadFileName; } @Override public String execute() throws Exception { FileOutputStream fos = new FileOutputStream(getSavePath() + "//" + getUploadFileName()); FileInputStream fis = new FileInputStream(getUpload()); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fis.close(); fos.close(); return SUCCESS; }}Struts.xml configuration file:
<package name="upload" extends="struts-default"> <action name="upload"> <param name="savePath">/upload</param> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> </action></package>
For Action class, two special properties are included:
These two attributes are used to encapsulate the file name of the uploaded file and the file type of the uploaded file. For Struts2, if the Form form contains a file field with name attribute xxx, the corresponding Action needs to use three attributes to encapsulate the information of the file field:
Through the above development process, we can see that it is indeed a simple thing to upload files through Struts2. What we need to do is to associate the file domain with a property of type File in Action, so that we can easily access the file content of the uploaded file. As for how Struts2 uses the Multipart parser, it is completely transparent to developers.
Manually implement file filtering
Many times, web applications do not allow users to upload freely. We need to limit the file type and file size uploaded by users, so file filtering must be performed during file upload. Now, we will manually implement upload file filtering.
Configure a new parameter in struts.xml to indicate the supported upload type:
<param name="allowTypes">image/png,image/gif,image/jpeg</param>
Add a validation function in Action:
// Verify @Overridepublic void validate(){ String filterResult = filterType(getAllowTypes().split(",")); if (filterResult != null) { addFieldError("upload", "The file type you want to upload is incorrect!"); }}public String filterType(String[] types){ String fileType = getFileContentType(); for (String type : types) { if (type.equals(fileType)) { return null; } } return ERROR;} This just implements the type judgment, and then implements the size verification based on length() method of the File class. But it's so troublesome, let's talk about a simpler statement.
Interceptor implements file filtering
Struts2 provides an interceptor for file upload, and file filtering can be more easily achieved by configuring an interceptor. FileUpload of file upload in Struts2. In order for the interceptor to work, you only need to configure the interceptor reference in the Action.
When configuring a fileUpload interceptor, you can specify two parameters for it:
<!-- Configure fileUpload interceptor--><interceptor-ref name="fileUpload"> <param name="allowedTypes">image/png,image/gif,image/jpeg</param> <param name="maximumSize">20000000</param></interceptor-ref><!-- Configure the system's default interceptor--><interceptor-ref name="defaultStack" /><result name="success">/success.jsp</result>
In this way, modifying the configuration can be done, which is really much easier than writing a piece of code.
Configuration error message
For upload errors, the system will prompt English error messages by default. However, in order to output international prompt messages, it is necessary to add the following two key message definitions to the international resource configuration file:
struts.messages.error.content.type.not.allowed = The upload file type is incorrect, please upload againstruts.messages.error.file.too.large = The file you uploaded is too large, please upload it againNext, you can use <s:fielderror/> to output the error message.
Constant configuration for file upload
At the beginning of the article, we talk about the configuration in default.properties , which has a struts.multipart.saveDir configuration. So what is the specific function of this configuration item?
During the process of Struts2 file upload, a temporary folder needs to be specified to store temporary files generated during the upload process; if no temporary folder is specified, the system defaults to using javax.servlet.context.tempdir , under the work/Catalina/localhost/ path under the Tomcat installation path. And this struts.multipart.saveDir configures the storage location of temporary files. Therefore, during the development process, you must pay attention to whether the directory has read and write permissions.
There is also a struts.multipart.maxSize configuration, which represents the size of the uploaded file. If the maximumSize property of this configuration and the maximumSize property of the fileUpload interceptor are specified at the same time, it will first compare with the maximumSize property of struts.multipart.maxSize configuration, and then compare with the maximumSize property of the fileUpload interceptor. If the file size exceeds the maximumSize configuration of struts.multipart.maxSize , an exception will appear and the Result will not be transferred to the input. Be sure to pay attention to this.
Summarize
This article summarizes the upload of files in Struts2 in detail. There are a lot of contents, basically all the contents in the manual. Well, just use it as a manual.
Okay, the above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.