Struts 2 notes -- File Download

Keywords: Java Struts xml Apache encoding

Struts 2 provides the stream result type, which is specifically used to support the file download function. The following four properties are required to configure the result of stream type.

contentType: Specifies the file type of the downloaded file

inputName: Specifies the entry input stream of the downloaded file

contentDisposition: Specifies the name of the downloaded file

bufferSize: Specifies the buffer size when downloading files


Example of struts 2 file download:

1. Handle the Action of file download:

 * Description:Struts2 Control file download
 * Author: Eleven
 * Date: 2018/1/24 10:39
public class FileAction extends ActionSupport{

    //The member variable corresponds to struts.xml in inputName Value,And provide 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/";
        //utilize getResourceAsStream()Convert the specified file to 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 put the downloaded file under the path of WEB-INF/images of the project. According to your own needs, you can directly 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" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

    <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-->
            <!--The configuration result type is stream Results of-->
            <result type="stream">
                <!--Specify the file type of the download file-->
                <param name="contentType">application/zip</param><!--image/jpg-->
                <!--Appoint action The InputStream Name of-->
                <param name="inputName">targetFile</param>
                <param name="contentDisposition">filename=""</param>
                <!--Specifies the buffer size of the download file-->
                <param name="bufferSize">4096</param>



Enter the access path of the corresponding file download in the browser address bar, such as http: / / localhost: 8080 / demo / file "download, and then download the file.

Posted by greeneel on Fri, 01 May 2020 21:03:00 -0700