Examples of Struts2 file uploads and downloads in Java _java

Source: Internet
Author: User
Tags constant html form uuid

File Upload

  1. Form Preparation
    • To upload one or more files using an HTML form
    • The enctype property of the HTML form must be set tomultipart/form-data
    • You must set the method property of the HTML form to post
    • You need <input type=“file”> to add a field.
  2. struts support for file uploads
    • in struts applications, FileUpload interceptors and Jakarta Commons FileUpload components can complete file uploads.
    • Step:
      1. Use the file label in the upload form for the JSP page. If you need to upload multiple files at once, you must use multiple file tags, but their names must be the same
      2. in Action Add 3 new and file upload related properties. The names of these 3 properties must be the following format
        • upload of basic files: Define the following 3 properties directly in the Action and provide the corresponding getter and setter
        • [File Name] : type-file-uploaded files . For example: data ( filename requirements and File table item Name consistent )
        • [File Name]contenttype : type-st Ring-file type for uploading files . For example: Datacontenttype ( to receive file type (MIME value) )
        • [File name]filename : strin G-File name of the uploaded files . For example: DataFileName ( name used to receive files )
      3. If you upload multiple files, you can use the List
        • If you pass multiple files, the above 3 attributes can be changed to the List type! The Name property value for multiple file fields needs to be consistent.
  3. Sample code
<s:form action= "Testupload" enctype= "Multipart/form-data" >
  <s:textfield name= "username[0" "label=" User-1 "></s:textfield>
  <s:file name=" photos "label=" photo "></s:file>
  <s:textfield Name = "Username[1]" label= "User-2" ></s:textfield>
  <s:file name= "photos" label= "photo" ></s:file>
  <s:textfield name= "username[2]" label= "user-3" ></s:textfield> <s:file name= "photos" label= "
  Photo "></s:file>
  <s:submit value=" Submit "></s:submit>
public class Uploadaction extends actionsupport{@Setter @getter private list<file> photos;
  @Setter @getter private list<string> photoscontenttype;
  @Setter @getter private list<string> photosfilename;

  @Setter @getter private list<string> userName;
    Public String Testupload () throws IOException {System.out.println ("UserName:" +username);
    System.out.println ("Photos:" +photos);
    System.out.println ("Photosfilename:" + photosfilename);

    System.out.println ("Photoscontenttype:" +photoscontenttype); Upload the file to the server root under Upload file//get ServletContext servletcontext ServletContext = Servletactioncontext.getservletcontex
    T ();
    Get the real path String Realpath = Servletcontext.getrealpath ("/upload");
    System.out.println (Realpath);
    File UploadFile = new file (Realpath);
    Determine if the path exists if (!uploadfile.exists ()) {//does not exist create uploadfile.mkdir (); for (int i = 0; i < photos.size (); i++) {uuid uuid = Uuid.raNdomuuid ();
    Fileutils.copyfile (Photos.get (i), new File (Realpath + "/" + UUID + photosfilename.get (i)));
  return SUCCESS;

 }
}

1. Deal with a few minor problems?

1. Duplicate file name, you can generally generate a UUID as a prefix before the filename.

2. Limit the size of individual files

3. Limit the type of file

4. Limit the size of the total file

2. FileUpload interceptors are provided in STRUTS2 to set these property values

The FileUpload Interceptor has 3 properties to set.

    • MaximumSize: Maximum length (in bytes) for uploading a single file, with a default value of 2 MB
    • Allowedtypes: Types of files allowed to be uploaded, comma-delimited between types
    • Allowedextensions: Allow file extensions to be uploaded, separated by commas between extension names
    • You can overwrite these 3 properties in the Struts.xml file

Note: There is a limit to the total size of the uploaded file in the default.properties under Org.apache.struts2. You can modify the limit by using a constant method struts.multipart.maxsize=2097152

<constant name= "Struts.devmode" value= "true"/> <!--Modify the size of the total file in this--> <constant name= "struts.multipart.m Axsize "value=" 2097152 "/> <package name=" Default "namespace="/"extends=" Struts-default "> <interceptors&
    Gt <interceptor-stack name= "Myinterceptor" > <interceptor-ref name= "Defaultstack" > <!--Modify a single file size,
        Commons fileupload Component Default Accept upload file Total maximum value is 2M--> <param name= "Fileupload.maximumsize" >57,408</param>
        <!--file types allowed to be uploaded--> <param name= "Fileupload.allowedtypes" >image/pjpeg,image/gif</param> <!--allow uploading of file extensions--> <param name= "fileupload.allowedextensions" >jpg,gif</param> </int erceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name= "Myinterceptor "></default-interceptor-ref> <action name=" testupload "class=" Org.pan.action.UploadAction "method=" Testupload "> <reSult name= "Success" >/WEB-INF/views/success.jsp</result> <result name= "Input" >/upload.jsp</
 Result> </action> </package>

A. Upload file related error messages?

1. Error messages related to file uploads are predefined in the Struts-messages.properties file.

2. Can be in the file upload Action corresponding to the resource file or in the I18n_zh_cn.properties internationalized resource file to redefine the error message

struts.messages.error.file.too.large=, the file you sent was too big.
struts.messages.error.content.type.not.allowed= file type error
struts.messages.error.file.extension.not.allowed= name extension Error
struts.messages.upload.error.sizelimitexceededexception= file total size exceeds upper limit

File download

  1. In some applications, it may be necessary to dynamically send a file to the user's browser, and the name and location of the file are not predictable when programmed

  2. Stream Result Type
    • Struts provides a Stream result type specifically for file downloads. When you use a Stream result, you do not have to prepare a JSP page.
    • The Stream result type can set the following parameters:
      • contentType: The MIME type of the file being downloaded. The default value is Text/plain
      • contentlength: The size, in bytes, of the downloaded file
      • contentdisposition: You can set the Contentdispositon response header for the download file name, the default value is inline, which is usually set to the following format:
        • Attachment;filename= "Document.pdf".
      • inputname: The input stream for the file provided in the Action. The default value is InputStream
      • buffersize: The size of the buffer when the file is downloaded. The default value is 1024
      • allowcaching : Allows caching to be used when downloading files. The default value is True
      • Contentcharset: Character encoding when downloading files.
        • The above parameters can be provided in the Action by getter Method!
    • The parameters of the Stream result type can be overridden by an Action in the form of an attribute
    • Detailed use details refer to struts-2.3.15.3-all/struts-2.3.15.3/docs/ww/docs/stream-result.html
  3. Sample code

<a href= "testdownload" > Download </a>
 public class Downloadaction extends actionsupport{//usually the following parameters are provided in the action @Setter @getter
  Private String ContentType;
  @Setter @getter Private Long contentlength;
  @Setter @getter private String contentdisposition;

  @Setter @getter private InputStream InputStream; Public String Testdownload () throws FileNotFoundException, unsupportedencodingexception {//Get ServletContext SERVL
    Etcontext ServletContext = Servletactioncontext.getservletcontext ();
    Gets the path of the file String Realpath = Servletcontext.getrealpath ("/web-inf/file/at least you. mp3");
    Gets the stream of the file InputStream = new FileInputStream (Realpath);
    Set the type of file ContentType = Servletcontext.getmimetype (Realpath);
    Gets the length of the file ContentLength = new file (realpath). Length ();
    Set filename String filename = "There's at least you. mp3";
    FileName = new String (filename.getbytes ("GBK"), "iso8859-1");
    Contentdisposition = "Attachment;filename=" +filename;
  return SUCCESS; }
}

<!--file Download-->
<action name= "testdownload" class= "org.pan.action.DownLoadAction" method= "Testdownload" >
  <result type= "Stream" >
    <!--file buffer size-->
    <param name= "buffersize" >2048</param >
  </result>
</action>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.