<a href="${pageContext.request.contextPath}/download?filename="+filename>点击下载</a>
在action类中执行完execute方法后返回成功字符串跳转到result之后再result中设置contentType、contentDisposition、inputStream
<result name="success" type="stream">
<param name="contentType">${contentType}</param>
<param name="contentDisposition">attchment;filename=${downloadFileName}</param>
<param name="inputStream">${inputStream}</param>
</result>
在action类中提供对应的getContentType、getDownloadFileName、getInputStream方法
public String getContentType() {
String mimeType = ServletActionContext.getServletContext().getMimeType(filename);
return mimeType;
}
public String getDownloadFileName() throws UnsupportedEncodingException {
return DownloadUtils.getDownloadFileName(ServletActionContext.getRequest().getHeader("user-agent"), filename);
}
public InputStream getInputStream() throws FileNotFoundException,UnsupportedEncodingException {
filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决中文名称乱码.
FileInputStream fis = new FileInputStream("d:/upload/" + filename);
return fis;
}
用DownloadUtils工具类来返回一个下载文件名,目的之为了去支持不同的浏览器,比如火狐用的是BASE64编码
public class DownloadUtils { public static String getDownloadFileName(String agent,String filename) throws UnsupportedEncodingException{ if(agent.contains("MSIE")){ //IE filename = URLEncoder.encode(filename,"utf-8"); }else if(agent.contains("Firefox")){ //火狐浏览器 BASE64Encoder base64Encoder = new BASE64Encoder(); filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?="; }else{ //其他浏览器 filename = URLEncoder.encode(filename,"utf-8"); } return filename; } }