Notes: Struts2 file upload and download

Source: Internet
Author: User
Tags create directory

in order to upload a file, the form's method must be set to POST, the enctype set to Muiltipart/form-data, and only set to this case. The browser will send the binary data of the user's selected files to the server.

  1. Upload Parser Configuration
    1. Struts2 does not provide its own request resolver,struts2 needs to invoke other upload frameworks to parse the binary data,struts2 by default using Jakarta Common-fileupload File Upload framework, you need to add Commons-io-2.2.jar in the lib of the Web application and Commons-fileupload-1.3.2.jar.
    2. Set the file upload parser by struts2 constant configuration struts.multipart.parser , default value Jakarta
    3. Struts.multipart.saveDir: The temporary file save path of the uploaded file, the default value javax.servlet.context.tempdir the configured path, the path is Tomcat Work\catalina\localhost under the installation path.
    4. Struts.multipart.maxSize: Maximum number of bytes for the entire form request content, default value 2097152
  2. upload Action parsing
    1. Create a field of type Java.io.File to receive the uploaded file stream, create xxxfilename and xxxcontenttype to read the original uploaded file name and file type, where xxx represents the field name of the Java.io.File type, such as the example is the file stream that receives the upload named the Upload field, so you need to have uploadfilename and /c8> Uploadcontenttype to receive the original file name and file type of the file stream, the sample code is as follows:

      ??

      public class Uploadaction extends Actionsupport {

      ??

      /**

      *

      */

      Private static final long serialversionuid = 283051583917637792L;

      ??

      Private File upload;

      Private String Uploadfilename;

      Private String Uploadcontenttype;

      Private String Uploadpath;

      ??

      Public Uploadaction () {

      Uploadpath = "Upload";

      }

      ??

      @Override

      Public String Execute () throws Exception {

      ??

      if (upload = = null) {

      Addactionerror (" no option to upload files ");

      return INPUT;

      }

      ??

      String FilePath = Servletactioncontext.getservletcontext (). Getrealpath (Uploadpath);

      ??

      Java.io.File dir = new Java.io.File (FilePath);

      if (dir.exists () = = False) {

      if (dir.mkdirs () = = False) {

      Addactionerror (" failed to create directory, directory path =" + FilePath);

      return INPUT;

      }

      }

      ??

      System.out.println ("Upload FileName =" + Uploadfilename);

      System.out.println ("Upload ContentType =" + Uploadcontenttype);

      ??

      FileOutputStream FileOutputStream = new FileOutputStream (FilePath + file.pathseparator + uploadfilename);

      FileInputStream FileInputStream = new FileInputStream (upload);

      byte[] buffer = new byte[4096];

      int len = 0;

      do {

      Len = fileinputstream.read (buffer, 0, buffer.length);

      if (Len > 0) {

      Fileoutputstream.write (buffer, 0, Len);

      }

      } while (len > 0);

      ??

      Addactionmessage (" upload complete, save path =" + FilePath + file.pathseparator + uploadfilename);

      ??

      return SUCCESS;

      }

      ??

      Public File Getupload () {

      return upload;

      }

      ??

      public void Setupload (File upload) {

      This.upload = upload;

      }

      ??

      Public String Getuploadfilename () {

      return uploadfilename;

      }

      ??

      public void Setuploadfilename (String uploadfilename) {

      This.uploadfilename = Uploadfilename;

      }

      ??

      Public String Getuploadcontenttype () {

      return uploadcontenttype;

      }

      ??

      public void Setuploadcontenttype (String uploadcontenttype) {

      This.uploadcontenttype = Uploadcontenttype;

      }

      }

  3. fileUpload Interceptor
    1. The FileUpload Interceptor is a file upload interceptor provided by struts2 that intercepts disallowed upload file types and file sizes and requires two parameters to be configured to handle:
      1. parameter allowedtypes: This parameter specifies the file types (ContentType) that are allowed to be uploaded, and multiple file types are separated by commas
      2. parameter maximumsize: This parameter specifies the size of the file that is allowed to be uploaded, per byte
    2. If the file type is uploaded or the file size is wrong,the FileUpload interceptor will read the global internationalized resource file to prompt and read the Key as follows:
      1. struts.messages.error.file.too.large: this key< Span style= "font-family: Microsoft Black" > indicates that the uploaded file is too large to prompt
        1. {0} means actionname
        2. {1}
        3. {2} Indicates the server temp file name
        4. {3} upload file ContentType
      2. struts.messages.error.content.type.not.allowed: This key indicates a prompt to upload file type errors
        1. {0} represents actionname
        2. {1} indicates the original file name was uploaded
        3. {2} indicates the server temp file name
        4. {3} byte size of uploaded file
        5. {4} allowed upload file byte size
      3. Struts.messages.error.uploading: This key indicates that an unknown error occurred while uploading the file.
    3. To configure the sample code

      <action name= "Upload" class= "org.drsoft.actions.file.UploadAction" >

      <interceptor-ref name= "FileUpload" >

      <param name= "Allowedtypes" >image/png</param>

      <param name= "MaximumSize" >102400</param>

      </interceptor-ref>

      <!-- must increase the item, and if you do not add another interceptor, it will add the interceptor by default--

      <interceptor-ref name= "Defaultstack"/>

    ??

    <result name= "Success" >/WEB-INF/content/file/upload.jsp</result>

    <result name= "Input" >/WEB-INF/content/file/upload.jsp</result>

    </action>

  4. Download file Action
    1. the Action to download the file requires the result type of stream, and thestream result type needs to specify a inputname parameter. This parameter specifies an input stream, which is the entry for the downloaded file, with the following detailed parameters:
      1. parameter inputname: The name of the download method that represents the return inputstream of its Action class , and the example, set to DownloadFile, invokes the getdownloadfile method for Action class
      2. parameter contentType: Set the mime-type of the HttpResponse, set the response ContentType Header, default value Text/plain, universal value application/octet-stream
      3. parameter contentdisposition: Sets the content disposition value of the response header to specify how the browser handles and downloads the file name, the default type is inline (inline), the browser will open the file, you can set attachment(attachment), the browser will prompt to save the file, parameter example: Inline;filename= "downloadfile.zip", If the file name is in Chinese, you need to use java.net.URLEncoder.encode (filename, "UTF-8")
      4. parameter contentlength: Sets the byte length of the stream for the browser's download progress display
      5. parameter buffersize: Buffer byte size for input stream and output stream
      6. parameter allowcaching: If set to false, The Cache-control of the response message header is set to No-cache , the default value is true
      7. parameter contentcharset: Set the content encoding, if set the value will be added to the X response message after the contentType appended "; charset= Value

        ??

    ??

??

Notes: Struts2 file upload and download

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.