zoukankan      html  css  js  c++  java
  • Struts2下载

    1). Struts2 中使用 type="stream" 的 result 进行下载即可

        <action name="testDownload" class="com.download.file.DownloadAction">
                <result name="success" type="stream"></result>
            </action>

    2). 具体使用细节参看 struts-2.3.15.3-all/struts-2.3.15.3/docs/WW/docs/stream-result.html

    3). 可以为 stream 的 result 设定如下参数

    contentType: 结果类型
    contentLength: 下载的文件的长度
    contentDisposition: 设定 Content-Dispositoin 响应头. 该响应头指定接应是一个文件下载类型, 一般取值为  attachment;filename="document.pdf".

    inputName: 指定文件输入流的 getter 定义的那个属性的名字. 默认为 inputStream

    bufferSize: 缓存的大小. 默认为 1024
    allowCaching: 是否允许使用缓存
    contentCharSet: 指定下载的字符集

    4). 以上参数可以在 Action 中以 getter 方法的方式提供!

    package com.download.file;
    
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    import javax.servlet.ServletContext;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class DownloadAction extends ActionSupport {
        private static final long serialVersionUID = 1L;
        private String contentType;      //结果类型
        private long contentLength;      //下载的文件的长度
        private String contentDisposition;   //设定 Content-Dispositoin 响应头. 该响应头指定接应是一个文件下载类型, 一般取值为  attachment;filename="document.pdf".
        private InputStream inputStream;    //指定文件输入流的 getter 定义的那个属性的名字. 默认为 inputStream
        
        
        public String getContentType() {
            return contentType;
        }
    
    
        public long getContentLength() {
            return contentLength;
        }
    
    
        public String getContentDisposition() {
            return contentDisposition;
        }
    
    
        public InputStream getInputStream() {
            return inputStream;
        }
    
    
        @Override
        public String execute() throws Exception {
            contentType="text/txt";
            contentDisposition = "attachment;filename=测试下载.txt";
            ServletContext servletContext = 
                    ServletActionContext.getServletContext();
            String fileName = servletContext.getRealPath("/files/测试下载.txt");
            inputStream = new FileInputStream(fileName);
            contentLength = inputStream.available();
            return super.execute();
        }
        
    }
  • 相关阅读:
    [GXOI/GZOI2019] 旧词
    [HDU6756] Finding a MEX
    [洛谷P5110] 块速递推
    [CF739C] Alyona and towers
    1349. 修理牛棚
    L2-028 秀恩爱分得快 (25 分)
    L2-009 抢红包 (25 分)
    L1-043 阅览室 (20 分)
    2020年天梯赛-模拟赛 L1-6 检查密码 (15 分)
    L1-046 整除光棍 (20 分)
  • 原文地址:https://www.cnblogs.com/bulrush/p/7773881.html
Copyright © 2011-2022 走看看