JSP页面:
<a href="${pageContext.request.contextPath }/download.action?filename=下载文件名.txt">下载文件</a>
Struts.xml:
<!-- 文件下载 -->
<action name="download" class="[].DownloadAction">
<result type="stream">
<!-- 使用默认流 名称 inputStream, 设置两个头 -->
<!-- 应该根据文件名 动态获得 MIME类型 -->
<!--
下载文件对应 MIME协议规定类型,动态获取
在Action 提供 getContentType方法
-->
<param name="contentType">${contentType}</param>
<!--
解析下载附件名 问题
inline浏览器内部打开, attachment 以附件形式打开
-->
<param name="contentDisposition">attachment;filename=${filename}</param>
</result>
</action>
文件下载原理: 服务器读取下载文件内容,通过Response响应流写回, 设置 ContentType、 ContentDisposition 头信息
关于下载的源文件:(Struts.xml配置)
public class StreamResult extends StrutsResultSupport {
protected String contentType = "text/plain"; // contentType头信息 (下载文件对应 MIME协议规定类型 )
* html --- text/html . txt--- text/plain
protected String contentDisposition = "inline"; // ContentDisposition头信息 (下载文件打开方式 inline浏览器内部打开, attachment 以附件形式打开)
protected String inputName = "inputStream"; // 需要Action中 提供 getInputStream 方法 返回 InputStream 提供下载文件 内容
}
文件下载java类:
public class DownloadAction extends ActionSupport {
private String filename;
public void setFilename(String filename) throws IOException {
// 文件名 get方式提交 乱码
this.filename = new String(filename.getBytes("ISO-8859-1"), "utf-8");
}
@Override
public String execute() throws Exception {
System.out.println("下载:" + filename);
// 文件下载 结果集 是一个流
return SUCCESS;
}
// 提供 下载文件 流
// 因为StreamResult中 protected String inputName = "inputStream";
public InputStream getInputStream() throws IOException {
// 下载文件输入流
File file = new File(ServletActionContext.getServletContext()
.getRealPath("/download") + "/" + filename);
return new FileInputStream(file);
}
// 根据下载文件名动态获得 MIME文件类型
public String getContentType() {
// 读取tomcat/conf/web.xml
return ServletActionContext.getServletContext().getMimeType(filename);
}
// 下载附件名 ${filename}
public String getFilename() throws IOException {
// 附件名乱码 问题 (IE和其它浏览器 : URL编码 , 火狐: Base64编码)
String agent = ServletActionContext.getRequest()
.getHeader("user-agent");
return encodeDownloadFilename(filename, agent);
}
/**
* 下载文件时,针对不同浏览器,进行附件名的编码
*
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
public String encodeDownloadFilename(String filename, String agent)
throws IOException {
if (agent.contains("Firefox")) { // 火狐浏览器
filename = "=?UTF-8?B?"
+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
+ "?=";
} else { // IE及其他浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}