读书人

struts2汉语言件支持迅雷下载

发布时间: 2013-10-08 16:32:36 作者: rapoo

struts2中文件支持迅雷下载

如果采用struts2中的stream模式,在迅雷下载时显示的文件名就会类似于XXXdownload.action这种,无法显示其真正的文件,如下所示:

配置文件:

<result name="download" type="stream">
<param name="contentType">${downloadContentType}</param>
<param name="inputName">downloadStream</param>
<param name="contentDisposition">user;filename="${downloadFileName}"</param>
<param name="bufferSize">4096</param>
</result>

后台代码:

downloadContentType = "application/vnd.ms-excel;charset=UTF-8";
downloadFileName = java.net.URLEncoder.encode(title, "UTF-8") +".xls";

ByteArrayOutputStream output = new ByteArrayOutputStream();
wb.write(output);

downloadStream = new ByteArrayInputStream(output.toByteArray());

return "download";

如图:

struts2汉语言件支持迅雷下载

为了实现迅雷下载时显示真正的文件名,将后台代码改成:

HttpServletResponse response = ServletActionContext.getResponse();

response.setContentType("application/octet-stream");
response.setHeader("content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");

String downloadPath = request.getSession().getServletContext().getRealPath("/WEB-INF/downloads");
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

FileOutputStream output = new FileOutputStream(downloadPath + "/" + sdf.format(now) + ".xls");

wb.write(output);
output.flush();
output.close();

//核心代码就下面这一行
request.getRequestDispatcher("/WEB-INF/downloads/" + sdf.format(now) + ".xls").forward(request, response);

return null;

修改后效果如图:

struts2汉语言件支持迅雷下载

前台链接记得加一个随机数,以免迅雷的秒传起作用

<%=basePath%>background/member_download.action?rnd=" + Math.random()

1楼wokao_wg昨天 19:09
mark

读书人网 >Web前端

热点推荐