使用Struts2的fileDownLoad下载文件

Struts2 jia包
———————-

    [Struts2 jar 下载地址](http://struts.apache.org/download.cgi)
-------------------

官方示例代码 具体使用细节参看 struts-2.3.15.3-all/struts-2.3.15.3/docs/stream-result.html
——— 以下内容来源[www.java1234.com]尚硅谷_Struts2 视频教程【主讲:佟刚】
文件的下载:

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

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 方法的方式提供
 <!-- struts2 xml配置-->
 <action name="testDownload" class="classPath">
        <result type="stream">
            <param name="bufferSize">2048</param>
        </result>
</action>

<!-- struts2 action类-->
    package com.atguigu.struts2.download.app;

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;
    private InputStream 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/html";
        contentDisposition = "attachment;filename=hidden.html";

        ServletContext servletContext = 
                ServletActionContext.getServletContext();
        String fileName = servletContext.getRealPath("/files/hidden.html");
        inputStream = new FileInputStream(fileName);
        contentLength = inputStream.available();

        return SUCCESS;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值