struts2 之 文件下载

1. 文件下载在应用系统使用也很常见。图片的下载,文件的下载,电影的下载。文件下载可以非常简单,通过超链接就可以直接下载。

<body>
   <a href="download/t.txt">诛仙</a><br/>
   <a href="download/jstl-1.2.jar">struts的jar包</a>
  </body>

但是通过超链接下载有一下问题:

如果浏览器能够读取文件,将会在浏览器中直接打开。没有好的方式来控制用户是否有权限下载。

2. 通过流的下载方式可以解决超链接的不足。实现步骤:

a) 编写Action

public class DownloadAction extends ActionSupport{
    private String fileName;
    //获取文件流
    public InputStream getInputStream() throws IOException{
        String path = ServletActionContext.getRequest().getRealPath("/download");
        return new FileInputStream(new File(path,fileName));
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

b)配置action:

<action name="download" class="cn.sxt.action.DownloadAction">
            <result type="stream">
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">attachment;filename=${fileName}</param>
            </result>
        </action>

c)jsp

<a href="download.action?fileName=t.txt">诛仙</a><br/>
   <a href="download.action?fileName=jstl-1.2.jar">struts的jar包</a>

3.文件下载Action的第二种写法:

public class DownloadAction extends ActionSupport{
    private String fileName;
    private InputStream inputStream;
    public String execute()throws IOException{
        String path = ServletActionContext.getRequest().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;
    }
}
原文地址:https://www.cnblogs.com/forever2h/p/6734040.html