您的位置:首页 > 编程语言 > Java开发

struts2中文件支持迅雷下载

2013-09-03 10:16 295 查看
如果采用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";

如图:



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

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;

修改后效果如图:



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

<%=basePath%>background/member_download.action?rnd=" + Math.random()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: