• 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;
        }
    }
  • 相关阅读:
    第三章 Jenkins参数及web项目
    第二章 Jenkins的详细介绍
    第一章 Git+Gitlab介绍和安装
    第二章 Centos7下Airflow2.1.0安装
    第一章 Airflow基本原理
    第五章 Pinpoint-Apm常见报错
    第四章 Docker方式安装 Pinpoint
    数论练习
    CF练习
    矩阵乘法
  • 原文地址:https://www.cnblogs.com/forever2h/p/6734040.html
Copyright © 2020-2023  润新知