Struts2 provides a stream result type, which is specifically used to support file downloading. The following 4 properties are required to specify the result of configuring the stream type.
contentType: Specify the file type of the downloaded file
inputName: Specify the entry input stream of the downloaded file
contentDisposition: Specify the downloaded file name
bufferSize: Specify the buffer size when downloading the file
Struts2 file download example:
1. Action to process file downloads:
/** * Description:Struts2 control file download* Author: Eleven * Date: 2018/1/24 10:39 */public class FileAction extends ActionSupport{ //This member variable corresponds to the value of inputName in struts.xml, and provides it with the get method private InputStream targetFile; //File download public String download(){ //Specify 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 into the corresponding input stream targetFile = ServletActionContext.getServletContext().getResourceAsStream(path); return SUCCESS; } //Provide get method public InputStream getTargetFile() { return targetFile; }}To download a file, you must first have the downloaded file resources. Here I place the downloaded file under the WEB-INF/images path of the project. You can do it according to your own needs, and 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_*" method="{1}"> <!--File download--> <!--Configure result type as stream--> <result type="stream"> <!--Specify file type of downloaded file--> <param name="contentType">application/zip</param><!--image/jpg--> <!--Specify the name of the InputStream that returns the downloaded file in the action--> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="aaa.zip"</param> <!--Specify the buffer size of 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 access path for the corresponding file download in the browser address bar, 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 to everyone's learning and I hope everyone will support Wulin.com more.