zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    图灵5月书讯※特别制作【MongoDB将在5月中旬隆重上市】
    让你学会狂妄懂得谦卑的书
    一千个读者,一千个不同的编程人生
    松本行弘为什么开发Ruby
    在Flex控件中使用XMLListCollection
    32位系统部署到64位下常见问题及解决
    win7系统的IIS服务器如何解除上传200k限制
    Asp.net单点登录解决方案
    Web.Config加密【转】
    在IIS8添加WCF服务支持
  • 原文地址:https://www.cnblogs.com/forever2h/p/6734040.html
Copyright © 2011-2022 走看看