• java之struts2之文件下载


    1.在实际应用开发中,文件下载功能也非常常见。

    2.最简单的文件下载方式是通过超链接来进行文件下载:

    <body>
        <a href="download/s.txt">课件</a><br/>
        <a href="download/t.jpg">美女</a><br/>
        <a href="download/jstl-1.2.jar">jstl</a>
    </body>

    注意:直接通过超链接下载文件,如果浏览器能够读取文件,浏览器会直接读取,而不会下载到本地。并且有安全问题。所以,可以通过action来实现下载。

    3.Struts2文件下载功能的实现:

    Action实现

    public class DownloadAction {
        private String fileName;
        public String execute(){
            return Action.SUCCESS;
        }
        //获取文件流
        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">
                    <!-- 根据inputName生产的get方法  到Action中去取得该方法的返回值 -->
                    <param name="inputName">inputStream</param>
                    <!-- 设置下载的文件 直接保存 -->
                    <param name="contentDisposition">attachment;filename=${fileName}</param>
                </result>
            </action>
        </package>

    jsp

    <body>
            <a href="download/2.txt">课件</a> <br />
            <a href="download/1.jpg">美女</a> <br />
            <hr />
            <a href="download.action?fileName=2.txt">课件</a> <br />
            <a href="download.action?fileName=1.jpg">美女</a> <br />
      </body>

    或者 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;
        }
    }
  • 相关阅读:
    《C#从现象到本质》读书笔记(八)第10章反射
    《C#从现象到本质》读书笔记(七)第9章 泛型
    《C#从现象到本质》读书笔记(六)第8章委托和事件
    《C#从现象到本质》读书笔记(五)第5章字符串第6章垃圾回收第7章异常与异常处理
    求1+2+……+n的和
    回溯法的应用举例
    回溯法
    翻转单词顺序列
    左旋转字符串
    和为S的两个数字
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/11161226.html
Copyright © 2020-2023  润新知