Struts2 implements simple file download.
Struts2 provides the stream result type, which is specially used to support file download. To configure the stream type, you must specify the following four attributes.
ContentType: Specifies the file type of the downloaded object.
InputName: Specifies the input stream of the object to be downloaded.
ContentDisposition: Specifies the downloaded file name.
BufferSize: Specifies the buffer size when downloading files.
Example of struts2 File Download:
1. Action for processing file downloads:
/*** Description: Struts2 Control File Download * Author: Eleven * Date: 2018/1/24 */public class FileAction extends ActionSupport {// This member variable corresponds to struts. the value of inputName in xml, and provide the get method private InputStream targetFile; // File download public String download () {// specifies the location of the downloaded resource, and return the corresponding input stream String path = "/WEB-INF/images/lib.zip"; // use getResourceAsStream () to convert the specified file to the corresponding input stream targetFile = ServletActionContext. getServletContext (). getResourceAsStream (path); return SUCCESS;} // provides the get method public InputStream getTargetFile () {return targetFile ;}}
File Download, first have to have downloaded file resources, here I will be downloaded files in the project's WEB-INF/images path, according to your own needs, then, use the getResourceAsStream () method provided by ServletContext to return the input stream corresponding to the specified file.
2. Configure struts. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.3 // EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name = "struts. enable. dynamicMethodInvocation "value =" false "/> <constant name =" struts. devMode "value =" true "/> <package name =" default "namespace ="/"extends =" struts-default "> <action name =" file _ * "class = "eleven. action. fileAction "method =" {1} "> <! -- File download --> <! -- Set the result type to stream --> <result type = "stream"> <! -- Specify the object type to download --> <param name = "contentType"> application/zip </param> <! -- Image/jpg --> <! -- Specify the name of InputStream in the action that returns the downloaded file --> <param name = "inputName"> targetFile </param> <param name = "contentDisposition"> filename = "aaa.zip" </param> <! -- Specify the buffer size of the downloaded file --> <param name = "bufferSize"> 4096 </param> </result> </action> </package> </struts>
Enter the corresponding file download access path in the address bar of the browser, such as http: // localhost: 8080/demo/file_download, to download the file. \
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.