struts.xml配置
<action name="download" class="com.report.util.DownloadAction">
<span style="white-space:pre"> </span><!-- 设置文件名参数,由页面上传入 -->
<param name="fileName"></param>
<result name="fileNotFound">error.jsp</result>
<result name="success" type="stream"><span style="font-family: Arial, Helvetica, sans-serif;"> </span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span><param name="contentType">text/plain</param></span><span style="font-family: Arial, Helvetica, sans-serif;"> </span>
<span style="white-space:pre"> </span><!-- 下载文件处理方法 -->
<span style="white-space:pre"> </span><param name="contentDisposition">attachment;filename="${downloadChineseFileName}"</param>
<span style="white-space:pre"> </span><!-- 下载文件输出流定义 -->
<span style="white-space:pre"> </span><param name="inputName">downloadFile</param>
</result>
</action>
设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名。这里使用的是动态文件名,${fileName}。它将通过 Action 的 getFileName() 获得文件名。也就是说Action里面要有一个getFileName ()的方法。
DownloadAction.java
public class DownloadAction extends ActionSupport{
//下载文件原始存放路径
private final static String DOWNLOADFILEPATH="/report/";
//文件名参数变量
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
//从下载文件原始存放路径读取得到文件输出流
public InputStream getDownloadFile() {
if(ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADFILEPATH+fileName) == null){
System.out.println("文件不存在!");
return null;
}
return ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADFILEPATH+fileName);
}
//如果下载文件名为中文,进行字符编码转换
public String getDownloadChineseFileName() {
<span style="white-space:pre"> </span>String downloadChineseFileName = fileName;
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>downloadChineseFileName = new String(downloadChineseFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
<span style="white-space:pre"> </span>return downloadChineseFileName;
}
public String execute() {
if(ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADFILEPATH+fileName) == null){
System.out.println("文件不存在!!!");
return "fileNotFound";
}
return SUCCESS;
}
}
contentType
内容类型,和互联网MIME标准中的规定类型一致,例如text/plain代表纯文本,text/xml表示XML,image/gif代表GIF图片,image/jpeg代表JPG图片
inputName
下载文件的来源流,对应着action类中某个类型为Inputstream的属性名,例如取值为inputStream的属性需要编写getInputStream()方法
contentDisposition
文件下载的处理方式,包括内联(inline)和附件(attachment)两种方式,而附件方式会弹出文件保存对话框,否则浏览器会尝试直接显示文件。取值为:
attachment;filename="struts2.txt",表示文件下载的时候保存的名字应为struts2.txt。如果直接写filename="struts2.txt",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于这样的写法:inline; filename="struts2.txt"
bufferSize
下载缓冲区的大小
。在这里面,contentType属性和contentDisposition分别对应着HTTP响应中的头Content-Type和Content-disposition头。