File download of java struts 2

Keywords: PHP Struts xml JSP

1. In practical application development, file download function is also very common.

2. The simplest way to download files is through hyperlink:

<body>
    <a href="download/s.txt">Courseware</a><br/>
    <a href="download/t.jpg">Beauty</a><br/>
    <a href="download/jstl-1.2.jar">jstl</a>
</body>

Note: download the file directly through the hyperlink. If the browser can read the file, the browser will read it directly instead of downloading it locally. And there are security issues. Therefore, you can download through action.

3. Implementation of the function of downloading Struts2 file:

Action implementation

public class DownloadAction {
    private String fileName;
    public String execute(){
        return Action.SUCCESS;
    }
    //Get file stream
    public InputStream getInputStream() throws FileNotFoundException{
        String path=ServletActionContext.getServletContext().getRealPath("/download");
        return new FileInputStream(new File(path,fileName));
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

Struts.xml

<package name="default" extends="struts-default" namespace="/">
        <action name="download" class="cn.sxt.action.DownloadAction">
            <result type="stream">
                <!-- according to inputName Productive get Method to Action To get the return value of the method -->
                <param name="inputName">inputStream</param>
                <!-- Set the download file to save directly -->
                <param name="contentDisposition">attachment;filename=${fileName}</param>
            </result>
        </action>
    </package>

jsp

<body>
        <a href="download/2.txt">Courseware</a> <br />
        <a href="download/1.jpg">Beauty</a> <br />
        <hr />
        <a href="download.action?fileName=2.txt">Courseware</a> <br />
        <a href="download.action?fileName=1.jpg">Beauty</a> <br />
  </body>

 

Or another way to write Action:

public class DownloadAction {
    private String fileName;
    private InputStream inputStream;
    public String execute() throws FileNotFoundException{
        String path=ServletActionContext.getServletContext().getRealPath("/download");
        inputStream =  new FileInputStream(new File(path,fileName));
        return Action.SUCCESS;
    }
    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

Posted by mattyj10 on Sun, 03 Nov 2019 02:51:01 -0800