jsp,href为get提交
<a href="${pageContext.request.contextPath }/demo02/download.action?filename=MIME协议简介.txt">MIME协议</a> <a href="${pageContext.request.contextPath }/demo02/download.action?filename=Struts2上传下载.ppt">Struts2上传下载.ppt</a> <a href="${pageContext.request.contextPath }/demo02/download.action?filename=老男孩.mp3">老男孩.mp3</a>
action
1、结果集类型使用stream,服务器端通过流的方式将文件发给客户端
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
查看StreamResult类,需要设置一个流,两个头
// contentType头信息 (下载文件对应 MIME协议规定类型 )* html --- text/html . txt--- text/plain protected String contentType = "text/plain"; // ContentDisposition头信息 (下载文件打开方式 inline浏览器内部打开, attachment 以附件形式打开) protected String contentDisposition = "inline"; // 需要Action中 提供 getInputStream 方法 返回 InputStream 提供下载文件 内容 protected String inputName = "inputStream";
2、获取InputStream数据流
3、获取文件MIME类型
4、根据不同浏览器设置下载时显示的文件名
5、get提交获取文件名乱码
public class DownloadAction extends ActionSupport { private String filename; @Override public String execute() throws Exception { return SUCCESS; } public void setFilename(String filename) throws UnsupportedEncodingException { this.filename = new String(filename.getBytes("ISO-8859-1"), "utf-8"); } public InputStream getInputStream() throws FileNotFoundException { File file = new File(ServletActionContext.getServletContext().getRealPath("/download") + "/" + filename); return new FileInputStream(file); } public String getContentType() { return ServletActionContext.getServletContext().getMimeType(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; } }
strtus配置,通过ognl访问Action中函数
<action name="download" class="demo02.DownloadAction"> <result type="stream"> <param name="contentType">${contentType}</param> <param name="contentDisposition">attachment;filename=${filename}</param> </result> </action>