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";

如图:

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

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()

发布了38 篇原创文章 · 获赞 4 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/tomatozq/article/details/10960579
今日推荐