jsp 下载 服务端的文件到本地

http://blog.csdn.net/arui_email/article/details/9041283


一、list页面的js,点击list列表下面的下载按钮调用js

[javascript]  view plain  copy
 print ?
  1. function downloadDoc(filePath,fileName){  
  2.     var path = filePath+fileName;  
  3.     var contextLength = "<%=request.getContextPath()%>";  
  4.     var sp = path.substring(contextLength.length,path.length);  
  5.     document.getElementById("path").value = sp;  
  6.     document.getElementById("fileName").value = fileName;  
  7.     //down_frame.location.href = path;decodeURI(path);encodeURIComponent  
  8.     var sForm1 = document.form1;  
  9.     sForm1.action = "<%=request.getContextPath()%>/com/icss/mdm/usermanual/servlet/StandardDocDownServlet";  
  10.     sForm1.submit();  
  11.      
  12. }  


下面是 一个form表单

[html]  view plain  copy
 print ?
  1. <form id="form1" name="form1" method="post">  
  2.     <input type="hidden" id="path" name="path"  />  
  3.     <input type="hidden" id="fileName" name="fileName"  />  
  4. </form>  


通过servlet的代码如下:

[java]  view plain  copy
 print ?
  1. package com.icss.mdm.usermanual.servlet;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import com.icss.mdm.base.servlet.BaseServlet;  
  5. import com.icss.pangu.logging.Log;  
  6. import com.icss.pangu.logging.LogFactory;  
  7.   
  8. public class StandardDocDownServlet extends BaseServlet {  
  9.     private static Log log = LogFactory.getLog(StandardDocDownServlet.class);  
  10.       
  11.     public void performTask(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  12.         String path = getParameter(request, "path"truetruefalse"");  
  13.         String fileName = getParameter(request, "fileName"truetruefalse"");  
  14.         request.setAttribute("path", path);  
  15.         request.setAttribute("fileName", fileName);  
  16.         if(!"".equals(path) && !"".equals(fileName)){//去函数说明文档页面  
  17.             getServletContext().getRequestDispatcher("/mdm/jsp/usermanual/DownFile.jsp").forward(request,response);  
  18.         }  
  19.          
  20.     }  
  21. }  


下面是下载的页面:

[html]  view plain  copy
 print ?
  1. <%@ page contentType="text/html;charset=GBK"%>  
  2. <%@page import="java.net.URLEncoder"%>  
  3.   
  4. <html>  
  5. <title>下载标准文档</title>  
  6.   
  7. <script language="javascript">  
  8. </script>  
  9. <body topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0">  
  10. <%  
  11.     //去除缓存   
  12.     /**response.setHeader("Pragma", "No-cache");  
  13.     response.setHeader("Cache-Control", "no-cache");  
  14.     response.setDateHeader("Expires", 0);  
  15.     String contextPath = request.getContextPath();**/  
  16.       
  17.     //String path = request.getParameter("path");  
  18.     //String fileName = request.getParameter("fileName");  
  19.     String path = (String)request.getAttribute("path");//即将下载的文件的相对路径  
  20.     String fileName = (String)request.getAttribute("fileName");//下载文件时显示的文件保存名称  
  21.       
  22.     response.setContentType("application/x-download");//设置为下载application/x-download  
  23.     String filedownload = path;//即将下载的文件的相对路径  
  24.     String filedisplay = fileName;//下载文件时显示的文件保存名称  
  25.     String filenamedisplay = URLEncoder.encode(filedisplay,"utf-8");  
  26.     response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);  
  27.        
  28.     try  
  29.     {  
  30.     RequestDispatcher dis = application.getRequestDispatcher(filedownload);  
  31.     if(dis!= null)  
  32.     {  
  33.     dis.forward(request,response);  
  34.     }  
  35.     response.flushBuffer();  
  36.     }  
  37.     catch(Exception e)  
  38.     {  
  39.     e.printStackTrace();  
  40.     }  
  41.     finally  
  42.     {  
  43.        
  44.     }  
  45. %>  
  46. </body>  
  47. </html>  

二、采用文件流输出的方式下载 

[html]  view plain  copy
 print ?
  1. <%@page language="java" contentType="application/x-msdownload" pageEncoding="gb2312"%>  
  2. <%  
  3.   //关于文件下载时采用文件流输出的方式处理:  
  4.   //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;  
  5.   
  6.   response.reset();//可以加也可以不加  
  7.   response.setContentType("application/x-download");  
  8.   
  9. //application.getRealPath("/main/mvplayer/CapSetup.msi");获取的物理路径  
  10.   
  11. String filedownload = "想办法找到要提供下载的文件的物理路径+文件名";  
  12.  String filedisplay = "给用户提供的下载文件名";  
  13.   String filedisplay = URLEncoder.encode(filedisplay,"UTF-8");  
  14.   response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);  
  15.   
  16.   java.io.OutputStream outp = null;  
  17.   java.io.FileInputStream in = null;  
  18.   try  
  19.   {  
  20.   outp = response.getOutputStream();  
  21.   in = new FileInputStream(filenamedownload);  
  22.   
  23.   byte[] b = new byte[1024];  
  24.   int i = 0;  
  25.   
  26.   while((i = in.read(b)) > 0)  
  27.   {  
  28.   outp.write(b, 0, i);  
  29.   }  
  30. //    
  31. outp.flush();  
  32. //要加以下两句话,否则会报错  
  33. //java.lang.IllegalStateException: getOutputStream() has already been called for //this response    
  34. out.clear();  
  35. out = pageContext.pushBody();  
  36. }  
  37.   catch(Exception e)  
  38.   {  
  39.   System.out.println("Error!");  
  40.   e.printStackTrace();  
  41.   }  
  42.   finally  
  43.   {  
  44.   if(in != null)  
  45.   {  
  46.   in.close();  
  47.   in = null;  
  48.   }  
  49. //这里不能关闭    
  50. //if(outp != null)  
  51.   //{  
  52.   //outp.close();  
  53.   //outp = null;  
  54.   //}  
  55.   }  
  56. %>  
[html]  view plain  copy
 print ?
  1. 备注:如何出现java.io.IOException: response already committed这个错误 则 把out.clear();out = pageContext.pushBody();这两个注释掉就可以解决了。  


 

[plain]  view plain  copy
 print ?
  1. 对于第二种方法,我认为应该是比较常用的。不过有几个地方是值得我们注意的:   
  2.   
  3. 一、采用第二种方法的主要优点是实际文件的存放路径对客户端来说是透明的。   
  4. 这个文件可以存在于任何你的服务器能够取得到的地方,而客户端不一定能直接得到。例如文件来自于数据库或者内部网络的一个FTP服务器。还句话说,这种方式可以实现隐藏实际文件的URL地址。   
  5.   
  6. 二、为了防止客户端浏览器直接打开目标文件(例如在装了MS Office套件的Windows中的IE浏览器可能就会直接在IE浏览器中打开你想下载的doc或者xls文件),你必须在响应头里加入强制下载的MIME类型:   
  7. response.setContentType("application/force-download");//设置为下载application/force-download   
  8. 这样,就可以保证在用户点击下载链接的时候浏览器一定会弹出提示窗口来询问你是下载还是直接打开并允许你选择要打开的应用程序,除非你设置了浏览器的一些默认行为。   
  9. 或者,你想让客户端自行处理各种不同的文件类型,你可以在服务器的配置文件中配置MIME类型映射,通过简单的判断文件后缀名来处理。例如,在Tomcat中设置MIME响应类型:   
  10. 如果文件在客户端中的响应程序类型和期望不一致,修改$TOMCAT_HOME\conf\web.xml文件中的如下部分 :   
  11. <mime-mapping>   
  12.   <extension>zip</extension>   
  13.   <mime-type>application/zip</mime-type>   
  14. </mime-mapping>   
  15. <mime-mapping>   
  16.   <extension>mht</extension>   
  17.   <mime-type>message/rfc822</mime-type>   
  18. </mime-mapping>   
  19. ……   
  20.   
  21. 三、在响应头中尽量不要设置浏览器缓存期限。   
  22. 有时候用户在点击了下载链接后,在弹出窗口中,用户想直接点击“打开”,而不想保存到指定路径。这时候如果我们在响应头中限制了不允许使用浏览器缓存(即总是刷新),在IE浏览器中我们将无法直接打开该文件。因为限制了不允许使用缓存,浏览器无法将文件保存到临时文件夹(即缓存)。   
  23. 也就是说,在响应头中不要进行如下的设置(已注释):   
  24.   //response.addHeader("pragma","NO-cache");   
  25.   //response.addHeader("Cache-Control","no-cache");   
  26.   //response.addDateHeader("Expries",0);   
  27.   
  28. 四、文件名为中文或其他unicode字符时的处理。   
  29. 有时候提供下载的文件名中包含中文字符或者其他unicode字符,会导致浏览器无法正确的采用默认的文件名保存文件。我们应该记住在响应头中包含filename字段并采用ISO8859-1编码(推荐)或者采用UTF-8编码:   
  30. response.setHeader("Content-disposition","attachment; filename="+new String(filename.getBytes("UTF-8"),"iso8859-1")); //采用ISO8859-1编码   
  31. response.setHeader("Content-disposition","attachment; filename="+URLEncoder.encode(filename, "UTF-8")); //采用UTF-8编码   
  32. 但是,这种方式在不同的浏览器中表现也有所不同。例如在IE和Firefox中,采用ISO8859-1编码可以正确显示文件名,而在Opera中不管采用那种编码,默认保存的文件名都无法做到正确显示。   
  33. 所以最好的方法其实就是尽量在文件名中使用ascii编码。   
  34.   
  35. 五、由于采用流的方式进行输入输出,我们必须保证在使用完毕后关闭流的资源。   
  36. 一般我们把关闭流的操作放在finally块中,以保证在程序段结束前一定会关闭流的资源:   
  37.   
  38. InputStream is = null;   
  39. ServletOutputStream sos = null;   
  40. try {   
  41.   is = ...; //通过某种方式读进数据到输入流   
  42.   sos = response.getOutputStream(); //打开输入流   
  43.   byte[] buff = new byte[2048];   
  44.   int bytesRead;   
  45.   while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {   
  46.   sos.write(buff,0,bytesRead);   
  47.   sos.flush();   
  48.   }   
  49. } catch(IOException ex) {   
  50.   //TODO something with IOException   
  51. } catch(Exception ex) {   
  52.   //TODO something with Exception   
  53. } finally {   
  54.   if(is != null) {   
  55.   is.close(); //关闭输入流   
  56.   }   
  57.   if(sos != null) {   
  58.   sos.close(); //关闭输入流   
  59.   }   
  60. }  


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值