<!-- 文件下载 -->
<action name="download" class="cn.action.demo2.DownloadAction">
<!-- 返回 流结果 -->
<result type="stream">
<!-- inputName 用于指定 返回输入流的方法名 默认值 inputStream -->
<!-- targetFile 需要在Action 中提供 getTargetFile方法,返回值必须InputStream -->
<param name="inputName">targetFile</param>
<!-- 配置ContentType -->
<!-- ${contentType}从Action中 getContentType 获得文件类型 -->
<param name="contentType">${contentType}</param>
<!-- 设置响应数据 以附件形式打开 -->
<param name="contentDisposition">attachment;filename=${filename}</param>
</result>
</action>
public class DownloadAction extends ActionSupport{
// 接收文件名
private String filename;
@Override
public String execute() throws Exception {
// 解决请求参数中文件名get乱码
filename = new String(filename.getBytes("ISO-8859-1"),"utf-8");
return SUCCESS;
}
public String getFilename() throws IOException {
// 对文件名 进行编码,用于附件下载
String agent = ServletActionContext.getRequest().getHeader("user-agent");
System.out.println(agent);
if(agent.contains("Firefox")){
// 火狐浏览器 Base64编码
return "=?UTF-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?=";
}else{
// IE及其它浏览器--- URL编码
return URLEncoder.encode(filename, "utf-8");
}
}
public void setFilename(String filename) {
this.filename = filename;
}
// getTargetFile方法名 因为配置 <param name="inputName">targetFile</param>
public InputStream getTargetFile() throws IOException{
// 获得download 目录 绝对路径
ServletContext servletContext = ServletActionContext.getServletContext();
String downloadDir = servletContext.getRealPath("/download");
return new BufferedInputStream(new FileInputStream(new File(downloadDir, filename)));
}
// <param name="contentType">${contentType}</param>
public String getContentType(){
// 文件类型 由文件名动态获得
ServletContext servletContext = ServletActionContext.getServletContext();
// 查找tomcat/conf/web.xml
return servletContext.getMimeType(filename);
}
}