当前位置:编程学习 > JAVA >>

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;
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,