用struts2输出文件流

有的时候超链接下载文件的方式并不能满足我们的需求,我们希望能够自己写回文件流,那么在struts2中如何做呢?

第一步,配置struts2.xml,示例如下:

<action name="ExcelAction" class="com.yingxia.trms.excel.ExcelAction">
    <result name="success" [color=red]type="stream"[/color]>
        <param name="contentType">application/vnd.ms-excel</param>
        <param name="contentDisposition">attachment; filename="${downloadChineseFileName}.xls"</param>
        <param name="inputName">outputStream</param>
    </result>
</action>
 


第二步,写action,这是一个示例的action(请忽略area和excelBiz)

package com.yingxia.trms.excel;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.google.inject.Inject;
import com.opensymphony.xwork2.Action;

public class ExcelAction {

    private String fileName;
    private String area;
    private InputStream outputStream;
   
    private ExcelBiz excelBiz;
   
    public String execute() throws Exception {
        excelBiz.generateExcel(area, fileName);
        outputStream = ServletActionContext.getServletContext().getResourceAsStream("excel/" + fileName + ".xls");
        return Action.SUCCESS;
    }
   
        // 解决下载中文文件名的问题
    public String getDownloadChineseFileName() throws UnsupportedEncodingException {
        return new String(fileName.getBytes(), "ISO8859-1");
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public InputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(InputStream outputStream) {
        this.outputStream = outputStream;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public ExcelBiz getExcelBiz() {
        return excelBiz;
    }

    @Inject
    public void setExcelBiz(ExcelBiz excelBiz) {
        this.excelBiz = excelBiz;
    }
   
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值