Struts2 file upload, as well as various precautions, struts2 File Upload
First of all, you must configure the struts2 environment. This is already described in another article, "setting up the struts2 environment and setting up a simple instance ".
The first part is the webpage section, upload_file.jsp
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %> <! Doctype html> To upload a file form, metho must be set to post, and enctype must be set to multipart/form-data.
From the code above, we can see that this form is submitted to the UploadFile action for processing. Then we configure the following in struts. xml:
<Action name = "UploadFile" class = "com. lidi. action. UploadAction"> <result name = "success">/uploadResult. jsp </result> <! -- FileUpload interceptor, which can be used to restrict the type and size of uploaded documents --> <interceptor-ref name = "fileUpload"> <! -- Limit the file size to 20 mb, in bytes --> <param name = "maximumSize"> 20971520 </param> </interceptor-ref> <! -- The default interceptor must be declared after the fileUpload interceptor --> <interceptor-ref name = "defaultStack"/> </action>
The fileUpload interceptor is used to set the upload path and limit the file type and size.
The <param name = "maximumSize"> file size cannot be restricted. You must add the <struts> label
<constant name="struts.multipart.maxSize" value="21000000"/>
This line of code indicates the maximum size of the files that can be uploaded in all parts of the project. That is to say, the size of each file uploaded in this project cannot exceed 21000000 bytes (about 20 mb ), if this line of code is not added to the project, the maximum file size allowed to be uploaded is 2 MB by default, which is beyond the limit that struts2 can only upload 2 MB files.
To restrict the file type to image files, <interceptor>
<! -- Set that only image files can be uploaded --> <intercepter-ref name = "fileUpload"> <param name = "allowedTypes"> image/bmp, image/x-png, image/gif, image/jpeg </param> </intercepter-ref> <interceptor-ref name = "defaultStack"/>
<Param name = "allowedTypes"> the values in the tag are all MIME types of files. The MIME types of common files can be found in % TOMCAT_HOME % \ conf \ web. xml.
If you want to restrict it to a word file, you can <interceptor> Configure it like this
<! -- Set to allow only the upload of Word documents --> <intercepter-ref name = "fileUpload"> <param name = "allowedTypes"> application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.doc ument </param> </intercepter-ref> <interceptor-ref name = "defaultStack"/>
However, I feel that it is better to limit the file type by using javascript on the front end.
Next, write UploadAction. The private attribute required by UploadAction is source, which is consistent with the name attribute of the file field in upload_file.jsp, that is, the name attribute value of the file field is source, the UploadAction must have the private property source. In addition, there are two important private properties:
Private String sourceFileName; // file name to be uploaded private String sourceContentType; // file type of the file to be uploaded
The format of these two variable names is the same as the name attribute of the file field in the prefix source and upload_file.jsp.
In general, for example, if the name of the file field in upload_file.jsp is "abc", the Action must be defined as follows:
private File abc;private String abcFileName;private String abcContentType;
Abc automatically obtains the object to be uploaded, abcFileName automatically obtains the file name, And abcContentType automatically obtains the file type.
I want to focus on the upload path.
It would be nice to upload the file to the absolute path. But if you want to upload the file to the upload folder under the root directory of the project, how can you obtain the complete path of the upload folder?
I tried to use
ServletActionContext.getServletContext().getRealPath("/upload");
However, null is returned. Also used
ServletActionContext.getRequest().getRealPath("/upload");
Or null is returned. However, I have found this problem on the Internet. Many people recommend this writing to prove that this writing may be feasible in some cases, but some people return null like me, they also recommended a new method to implement the ServletContextAware interface in UploadAction. The procedure is as follows:
Public class UploadAction extends ActionSupport implements ServletContextAware {/*** omitting other code... */private ServletContext context; public ServletContext getContext () {return context;} public void setContext (ServletContext context) {this. context = context;} @ Override public void setServletContext (ServletContext context) {this. context = context ;}}
Then use
String path = context. getRealPath ("/upload"); // important: the number of slashes cannot be small.
Obtain the path of the upload folder. Then execute the upload:
/* Upload the File to the upload folder */File savefile = new File (path, sourceFileName); FileUtils. copyFile (source, savefile );
I personally recommend this method because it seems to avoid ensuring the correct path when the project is packaged and transferred to other environments.
UploadAction. java
Package com. lidi. action; import java. io. file; import java. io. IOException; import javax. servlet. servletContext; import org. apache. commons. io. fileUtils; import org. apache. struts2.util. servletContextAware; import com. opensymphony. xwork2.ActionSupport; public class UploadAction extends ActionSupport implements ServletContextAware {/*****/private static final long serialVersionUID = 1L; private File source; // private String sourceFileName; // file name to be uploaded private String sourceContentType; // file type private ServletContext context; // important/* Important */public ServletContext getContext () {return context;} public void setContext (ServletContext context) {this. context = context;}/* getters & setters */public File getSource () {return source;} public void setSource (File source) {this. source = source;} public String getSourceFileName () {return sourceFileName;} public void setSourceFileName (String sourceFileName) {this. sourceFileName = sourceFileName;} public String getSourceContentType () {return sourceContentType;} public void setSourceContentType (String sourceContentType) {this. sourceContentType = sourceContentType;} @ Override public void setServletContext (ServletContext context) {this. context = context;} public String execute () throws IOException {/* obtain the path for storing the uploaded files: the upload folder in the project root directory */String path; path = context. getRealPath ("/upload"); // important: the System cannot contain fewer slashes. out. println (path);/* upload the File to the upload folder */File savefile = new File (path, sourceFileName); FileUtils. copyFile (source, savefile); System. out. println (savefile. getAbsolutePath (); return SUCCESS ;}}View code
Upload result page uploadResult. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib uri ="/struts-tags "prefix =" s "%> <! Doctype html>