Java Struts2 File upload problem detailed _java

Source: Internet
Author: User

First is the page section, upload_file.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <!
DOCTYPE html>
 
 

To upload the file form, the Metho must be set to Post,enctype must be set to Multipart/form-data.

From the code above you can see that this form is submitted to uploadfile this action to deal with, then we are configured in the Struts.xml as follows:

<action name= "UploadFile" class= "com.lidi.action.UploadAction" >
  <result name= "Success" >/ Uploadresult.jsp</result>
  <!--FileUpload Interceptor, which can be used to limit the type and document size of the uploaded document-->
  <interceptor-ref name= " FileUpload ">
  <!--limit file size 20M, bytes-->
    <param name=" MaximumSize ">20971520</param>
  </interceptor-ref>
  <!--default Interceptor, which must be declared after the FileUpload interceptor-->
  <interceptor-ref name= " Defaultstack "/>
 </action>

FileUpload Interceptor for setting the upload path, limiting file type and size.

Regarding the limit file size, the light has <param name= "MaximumSize" > is not possible, also must add under the <struts> label

<constant name= "struts.multipart.maxSize" value= "21000000"/>

This line of code represents the entire project to upload files to the maximum size of the file allowed to upload, that is, the project upload any single file size can not exceed 21000000 bytes (about 20M), if the project does not add this line of code, the default allowed to upload the maximum size of the file is 2M, So it's also a way to break through the limitations of struts2 uploading only 2M files.

For restrictions on file types, if you need to limit them to picture files, then <interceptor> can configure

<!--settings only allow uploading picture files-->
<intercepter-ref name= "FileUpload" >
  <param name= "Allowedtypes" > Image/bmp, Image/x-png, Image/gif, image/jpeg</param>
</intercepter-ref>
<interceptor-ref Name= "Defaultstack"/>

The values in the <param name= "allowedtypes" > tags are mime types of files, and the MIME types of common files can be found in%tomcat_home%\conf\web.xml.

If you want to restrict to a Word file, you can <interceptor> configure this

<!--settings allow only uploading Word documents-->
<intercepter-ref name= "FileUpload" >
  <param name= "Allowedtypes" > Application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
</intercepter-ref>
<interceptor-ref name= "Defaultstack"/>

However, I feel that it is better to restrict file types than to use JavaScript to implement the restrictions on the front end.

Next write uploadaction,uploadaction the required private property is source, which is and Upload_ File.jsp the Name property of the file field is consistent, that is, the Name property value of the file field is source, the private property source must be in uploadaction, and there are two more important private properties:

Private String sourceFileName; filename of file to be uploaded
Private String Sourcecontenttype; File type of file to upload
The two variable names are in the same format as the previous prefix source and the Name property of the File field in upload_file.jsp.

In combination, that is, for example, the name of the file field in upload_file.jsp = "abc", which is defined in action

Private File ABC;
Private String abcfilename;
Private String Abccontenttype; 

ABC automatically gets the file object to upload, Abcfilename automatically gets the filename, and Abccontenttype automatically gets the file type.

About the upload path, I would like to focus on the point.

If it's uploaded to the absolute path, that's pretty good, but if you want to upload the upload folder to the root of the project, how do you get the full path to the upload folder?

I have tried to use

Servletactioncontext.getservletcontext (). Getrealpath ("/upload");
However, NULL is returned. I used it.

Servletactioncontext.getrequest (). Getrealpath ("/upload");
or null is returned. But look up this problem on the Internet, many people recommend this, prove that it is possible to write in some cases is indeed feasible, but also have the same as I return null people, they also recommend a new method, is to let uploadaction implement Servletcontextaware interface. The following are specific practices:

public class Uploadaction extends Actionsupport implements Servletcontextaware {

  /**
   * Omit 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;
  }
}

and then use

String Path = Context.getrealpath ("/upload");/important: Slash not less

Gets the path to the upload folder. And then perform the upload:

/* Upload files to upload folder/file
savefile = new file (path, sourcefilename);
Fileutils.copyfile (source, savefile);

I personally recommend this approach, because it seems to circumvent the fact that when a project is packaged and transferred to another environment, it is guaranteed to get the right path.

The full code behind the uploadaction is attached 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;//to upload file private string sourcefilename;//file name to be uploaded private string sourcecontenttype; File type to upload file 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;
    The public String execute () throws IOException {/* Gets the path to the uploaded file: The project root directory Upload folder */String path;    
    Path = Context.getrealpath ("/upload");//Important: Slash cannot be less System.out.println (path);
    /* Upload files to upload folder/file SaveFile = new file (path, sourcefilename);
    Fileutils.copyfile (source, savefile);
    System.out.println (Savefile.getabsolutepath ());
  return SUCCESS;

 }
}

Upload results page uploadresult.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib uri=
"/struts-tags" Prefix= "s"%>
<! DOCTYPE html>
 
 

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.