struts2 之 文件下载

1. 文件下载在应用系统使用也很常见。图片的下载,文件的下载,电影的下载。文件下载能够很是简单,经过超连接就能够直接下载。浏览器

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

可是经过超连接下载有一下问题:jsp

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

2. 经过流的下载方式能够解决超连接的不足。实现步骤:spa

a) 编写Action

code

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:blog

<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的第二种写法:get

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;
    }
}
相关文章
相关标签/搜索