Java programmers from stupid birds to cainiao () detailed introduction to how struts2 implements file upload and download

Source: Internet
Author: User

File Upload and File Download are two common functions in Web applications. In Java, there are also many ways to implement these two functions, here, struts2 provides us with a relatively simple method. Let's take a look at it. First, let's look at file upload:


File Upload

When uploading files, we should first note the form on the upload page. This form is also exquisite, because the data in the submitted form contains file upload, therefore, the encoding type used for this form cannot be the original one. Here we should use the multipart/form-data encoding method and use the POST method for data submission, let's take a look:

Form. jsp:

<Form action = "studentaction! Addstu "target =" mainframe "onsubmit =" javascript: window. close () "method =" Post "enctype =" multipart/form-Data "> <Table class =" ta "width =" 200px "> <TD> name </TD> <TD> <input type = "text" name = "Stu. name "value =" $ {request. stu_info.name} "/> </TD> </tr> <tr bgcolor =" #6fdd0 "> <TD> upload Avatar </TD> <input type =" File "Name =" file "/> </TD> </tr> <tr bgcolor =" #6fdd0 "> <TD colspan =" 2 "> <input type =" Submit" value = "Submit" class = "bustyle"/> <input type = "reset" value = "reset" class = "bustyle"/> </TD> </tr> </table> </form>

OK. After reading the form, let's take a look at how the action receives the data. In fact, it is also very simple to define three variables in the action, these three variables are file, file name, and file type, as shown below:

private File file;private String fileFileName;private String fileContentType;

The names of these three variables are exquisite. If they are not just named, they are OK. The variable name file must be the same as the name of the file in the form, and the filefilename variable is also fixed, the naming format is name + filename, and the same is true for filecontenttype. The naming rule is name + contenttype. Only when you define variables according to naming rules can struts2 collect file upload information. OK. After reading the variable settings, let's take a look at how struts2 uploads the file to the specified location. Let's start with the code and let the Code help us understand:

String root = servletactioncontext. getrequest (). getrealpath ("/upload"); try {inputstream is = new fileinputstream (File); // create a file with the path root, file Name: filefilename // custom file name: filefilename = "111" + filefilename. substring (filefilename. lastindexof (". "); file destfile = new file (root, filefilename); // start uploading outputstream OS = new fileoutputstream (destfile); byte [] buffer = new byte [50000]; int length = 0; // enctype = "multipar T/form-Data "while (-1! = (Length = is. Read (buffer) {OS. Write (buffer, 0, length );}

We can see that there are several simple lines of code, but it is not difficult. It mainly uses the IO stream to upload files. After a single file is uploaded, it is not difficult to implement multi-file upload.


Multi-File Upload

Similar to single-file upload, Struts 2 implements Multifile upload. You can use multiple <s: File/> to bind an array or list of actions.

< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >     < s:file label ="File (1)" name ="upload" />     < s:file label ="File (2)" name ="upload" />     < s:file label ="FIle (3)" name ="upload" />     < s:submit /> </ s:form >


If you want to bind to an array, the Action Code should be similar:

  private File[] uploads;     private String[] uploadFileNames;     private String[] uploadContentTypes;     public File[] getUpload() { return this .uploads; }      public void setUpload(File[] upload) { this .uploads = upload; }       public String[] getUploadFileName() { return this .uploadFileNames; }      public void setUploadFileName(String[] uploadFileName) { this .uploadFileNames = uploadFileName; }       public String[] getUploadContentType() { return this .uploadContentTypes; }      public void setUploadContentType(String[] uploadContentType) { this .uploadContentTypes = uploadContentType; }

If you want to bind to the list, it should be similar:


private List < File > uploads = new ArrayList < File > ();     private List < String > uploadFileNames = new ArrayList < String > ();     private List < String > uploadContentTypes = new ArrayList < String > ();     public List < File > getUpload() {         return this .uploads;    }      public void setUpload(List < File > uploads) {         this .uploads = uploads;    }       public List < String > getUploadFileName() {         return this .uploadFileNames;    }      public void setUploadFileName(List < String > uploadFileNames) {         this .uploadFileNames = uploadFileNames;    }       public List < String > getUploadContentType() {         return this .uploadContentTypes;    }      public void setUploadContentType(List < String > contentTypes) {         this .uploadContentTypes = contentTypes;    }

After the data is collected, the file upload steps are the same as those of the preceding single file. This will not be repeated. Okay. Let's talk about this first when uploading files. Next, let's take a look at the file download.

File Download

Struts 2 provides direct support for file downloads. It is much easier to implement file downloads than setting various HTTP headers. When talking about file downloading, I am afraid the most direct method is to directly write a hyperlink so that the address is equal to the downloaded file. For example: <a href?#file1.zip "> download file1.zip </a>, then, you can click this link in the browser to download it. However, it has some defects. For example, if the address is an image, the browser will open it directly instead of displaying the dialog box for saving the file. For example, if the file name is Chinese, it will display a bunch of URL-encoded file names such as % 3457 .... Assume that you attempt to download the file: http: // localhost: 8080/struts2/download/java .doc. Tomcat will tell you the 404 error that a file cannot be found: HTTP status 404-/struts2hello/download/has been downloaded successfully. Doc. So here we will use the File Download provided by struts for us. Let's take a look at the download of the file provided by struts2:

In fact, the downloading of the files provided by struts2 is very simple. You can write a common action. You only need to provide a method to return the inputstream stream, the input stream represents the entrance to the downloaded file. This method is used to provide the input stream for the downloaded data, which means to read the stream and write it to the browser for download. This method needs to be compiled by the developer. You only need to return the value of inputstream. First, let's take a look at the JSP page:

<Body> 

The page is very simple. Just click the download link and link it to our action. Next, let's take a look at the compilation of our action:

Public class downaction extends actionsupport {Private Static final long serialversionuid = 1l; private string inputpath; Public String getinputpath () {return inputpath;} public void setinputpath (string inputpath) {This. inputpath = inputpath;}/** the action used for downloading should return an inputstream instance. This method corresponds to the inputname attribute in the result as * getdownloadfile */Public inputstream getdownloadfile () {return servletactioncontext. getservletcontext (). getresourceasstream ("/upload/struts2.txt");} Public String execute () throws exception {
return SUCCESS;
}
}

Let's take a look at the Struts. xml configuration:

<Action name = "down" class = "cn. csdn. hr. Up. Action. downaction"> <! -- Set the result type to stream --> <result name = "success" type = "stream"> <! -- Specify the file type of the downloaded file --> <Param name = "contenttype"> text/plain </param> <! -- Specify the location of the downloaded file --> <Param name = "contentdisposition"> attachment; filename = "struts2.txt" </param> <Param name = "inputname"> downloadfile </param> </result> </Action>

This action is special because the result type is a stream. When you configure the stream type result, you do not need to specify the actual physical resources displayed, so you do not need to specify the location attribute, you only need to specify the inputname attribute, which points to the source of the downloaded file and corresponds to an attribute in the action class. The type is inputstream. The following lists some download-related parameters:

Parameter description

Contenttype

Content type, which is consistent with the specified types in Internet mime standards. For example, text/plain indicates plain text, text/XML indicates XML, image/GIF indicates GIF image, and image/JPEG indicates jpg image.

Inputname

The source code of the downloaded file corresponds to the attribute name of an inputstream type in the action class. For example, if the value is an inputstream attribute, you must compile the getinputstream () method.

Contentdisposition

The file download process includes inline and attachment. The File Save dialog box is displayed. Otherwise, the browser tries to display the file directly. Value: attachment; filename = "struts2.txt". When the local file is downloaded, the name to be saved must be struts2.txt. If you directly write filename = "struts2.txt", the default value is inline. the browser will try to open it automatically, which is equivalent to the following statement: inline; filename = "struts2.txt"

Buffersize

Download buffer size

Here, the contenttype attribute and contentdisposition correspond to the header content-type and content-Disposition headers in the HTTP response respectively.


Of course, in many cases, we generally do not write the file name to the xml configuration. We usually define a variable downfilename in the action, store the file name, and then configure the XML:

 <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>

We often encounter garbled file names during Chinese downloads. This problem is common to many people, and there is no specific solution, however, I tried to re-code him when I used it. This can solve the problem of garbled Chinese downloading in most cases, but sometimes it doesn't work. The specific re-encoding is:

downFileName = new String(downFileName.getBytes(), "ISO8859-1");    

Now, let's briefly introduce the upload and download of the struts2 file. If there is anything wrong or wrong in the article, please let us know.

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.