有的时候超链接下载文件的方式并不能满足我们的需求,我们希望能够自己写回文件流,那么在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;
}
}