For Struts2 file download, Struts2 File Download

Source: Internet
Author: User
Tags mime file

For Struts2 file download, Struts2 File Download

First, let's talk about the principle of File Download:

The server provides a download service for the client. Therefore, the server needs an output stream (output the file requested by the client). Compared with the server, the client needs to download and receive a file, therefore, it requires an input stream (receiving file ).

The server reads the content of the file to be downloaded, writes back the content with a Response stream, and sets the HTTP header information ContentType and ContentDisposition)

The following is a small Demo. Let's analyze the specific code.

 

1. the download page: download. jsp

Give a hyperlink to Action and pass a file name in Get mode for property injection.

1 <% @ page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> 2 <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" http://www.w3.org/TR/html4/loose.dtd "> 3 

 

2. In addition to the Action for downloading files: DowloadAction. java

Here, a member variable is provided to receive the file name transmitted from the page. Because the file name is transmitted in Get mode, Chinese characters may encounter garbled characters, so we need to do some processing in the setter method, that is, re-encoding.

1 package com. lcw. struts2.dowload; 2 3 import java. io. file; 4 import java. io. fileInputStream; 5 import java. io. fileNotFoundException; 6 import java. io. IOException; 7 import java. io. inputStream; 8 import java. io. unsupportedEncodingException; 9 import java.net. URLEncoder; 10 11 import org. apache. struts2.ServletActionContext; 12 13 import sun. misc. BASE64Encoder; 14 15 import com. opensymphony. xwork2.Actio NSupport; 16/** 17 * for the client, it needs to download and receive a file, that is, it needs an input stream 18 * for the server, it needs to provide an external download service, that is to say, it requires an output stream 19 */20 21 public class DowloadAction extends ActionSupport {22 23 private String filename; // this parameter is passed on the download page, the setter method must be provided to receive 24 25 public void setFilename (String filename) {26 // Chinese characters may be garbled and cannot be obtained directly due to the get method, transcoding 27 try {28 this. filename = new String (filename. getBytes ("ISO-8859-1"), "UTF-8"); 29} catch (UnsupportedEncoding Exception e) {30 e. printStackTrace (); 31} 32} 33 34 public String execute () {35 System. out. println ("downloading file:" + filename); 36 return SUCCESS; 37} 38 39 // provide the input stream 40 public InputStream getInputStream () for the client () throws FileNotFoundException {41 String srcFile = ServletActionContext. getServletContext (). getRealPath ("/download") + "/" + filename; 42 File file = new File (srcFile); // get a file object 43 return new FileInputStream (file ); // Return a file input stream 44} 45 46 // provide the MIME file type 47 public String getContentType () {48 // web in Tomcat Conf dynamically based on different files. xml has the corresponding ing file 49 return ServletActionContext. getServletContext (). getMimeType (filename); 50} 51 52 // a file named 53 public String getFilename () throws IOException {54 String agent = ServletActionContext is returned. getRequest (). getHeader ("user-agent"); // obtain the corresponding browser type 55 return encodeDownloadFilename (filename, agent) based on the http header information; 56} 57 58 59 // The attachment name is garbled during downloading. for IE and Firefox, Url encoding is used by default. Firefox uses base64 encoding 60 public String encodeDownloadFilename (String filename, String agent) 61 throws IOException {62 if (agent. contains ("Firefox") {// Firefox 63 filename = "=? UTF-8? B? "64 + new BASE64Encoder (). encode (filename. getBytes (" UTF-8 ") 65 + "? = "; 66} else {// IE and other browsers 67 filename = URLEncoder. encode (filename," UTF-8 "); 68} 69 return filename; 70} 71}

After reading the above Code, it may be a bit confusing for a friend who does not belong to this part. Don't worry. Let me explain how this code came from.

First, the Struts2 file is downloaded through a result set Stream. In the Struts2 core package, we can find the following sentence:

<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>

Let's take a look at what is in this class. Ctrl + Shift + T associates with the source code.

This class provides a lot of parameters, because there are default values, so we don't need to change it all, just change what we need.

Here we will explain the parameter content in the red box above: contentType, contentDisposition, inputName

ContetType: the MIME protocol type corresponding to the downloaded file, for example, text/html, text/plain. We cannot write this parameter because there are many download file types, sometimes images or documents.

ContentDisposition: indicates how to open the downloaded file. inline, or inline, is used in the browser by default. If you do not want to associate the browser, you can set it to attment to open it as an attachment.

InputNmae: this is the name that defines a returned stream (the input stream required by the client). The attribute value is inputStream.

 

Therefore, we need to provide these items in the Action, and use the JAVA reflection mechanism to read the Struts2 configuration file (pushed to the value stack and the getter method.

Here, the name of the downloaded attachment will still contain garbled characters, because the default encoding of IE and other browsers is URL, and the default encoding of Firefox is BASE64. Here, we need to determine which browser the client uses, this is simple. You only need to get the HTTP header information Agment of the client. The specific code is provided in the above encodeDownloadFilename method.

 

3. Let's take a look at the configuration of the configuration file struts. xml:

Because the getter method of the required parameters has been provided in the Action, we need to use the Ognl expression here to obtain the required parameters dynamically based on the file to be downloaded, if no parameter is set, the default value is retained.

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! DOCTYPE struts PUBLIC 3 "-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 <struts> 6 <constant name = "struts. devMode "value =" true "/> 7 8 <! -- Global configuration --> 9 <constant name = "struts. custom. i18n. resources "value =" messages "> </constant> 10 11 <package name =" struts2test "extends =" struts-default "> 12 <action name =" download "class =" com. lcw. struts2.dowload. dowloadAction "> 13 <result type =" stream "> 14 <! -- A stream with two heads --> 15 <! -- Ognl expression, which dynamically gives the types specified by the MIME protocol corresponding to different download files, for example, text/html --> 16 <! -- The getContentType stack is provided in the Action --> 17 <param name = "contentType" >$ {contentType} </param> 18 <! -- Open the downloaded file in the inline browser and attachment in the form of attachments --> 19 <! -- Dynamically return the file name getFilename in the Action --> 20 <param name = "contentDisposition"> attachment; filename =$ {filename} </param> 21 </result> 22 </action> 23 </package> 24 25 </struts>

 

Then we create a new folder download to put the file to be downloaded in the same way as the file name provided on the web page.

Here we are all done. Let's take a look at the page effect:


Download java struts2 files

No prompts? No print statement is displayed?
Public String execute () throws ManagerException {
Return SUCCESS
}
Whether the statement is executed and success is returned

Struts2 File Download

Step 1:
First, you have an attribute in your Action class (the file name you want to dynamically set). You must have the getter method to get this attribute:

Private String fileName = "struts.jpg ";

Public String getFileName (){
Return fileName;
}
Step 2:
Configure struts. xml and use the expression language to dynamically obtain the file name in the Action class:
<Param name = "contentDisposition"> attachment; filename = "$ {fileName}" </param>
Over, hope to adopt, seek points

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.