Response實現文件下載


使用Myeclipse 工具

       在WebRoot目錄下創建一個Download文件夾(new-->folder),以存放 附件(圖片,文件...),

 

具體實現下載功能的代碼如下:

 

[java]  view plain copy
  1. package cn.response;  
  2.   
  3. import java.io.*;  
  4. import java.net.URLEncoder;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. //response實現從服務器上,下載文件  
  12. public class Response_download extends HttpServlet {  
  13.   
  14.   
  15.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  16.             throws ServletException, IOException {  
  17.         String path = this.getServletContext().getRealPath("/Download/定南中學.jpg");//獲取文件的相對路徑  
  18.         String filename = path.substring(path.lastIndexOf("\\")+1);//獲取文件名稱,在轉化為子串  
  19.         //response.setHeader告訴瀏覽器以什么方式打開  
  20.         //假如文件名稱是中文則要使用 URLEncoder.encode()編碼  
  21.         //否則直接使用response.setHeader("content-disposition", "attachment;filename=" + filename);即可  
  22.         response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));  
  23.           
  24.         InputStream in = null ;  
  25.         OutputStream out = null ;  
  26.         try  
  27.         {  
  28.            in = new FileInputStream(path); //獲取文件的流  
  29.            int len = 0;  
  30.            byte buf[] = new byte[1024];//緩存作用  
  31.            out = response.getOutputStream();//輸出流  
  32.            while( (len = in.read(buf)) > 0 ) //切忌這后面不能加 分號 ”;“  
  33.            {  
  34.                out.write(buf, 0, len);//向客戶端輸出,實際是把數據存放在response中,然后web服務器再去response中讀取  
  35.            }  
  36.         }finally  
  37.         {  
  38.             if(in!=null)  
  39.             {  
  40.               try{                
  41.                   in.close();  
  42.               }catch(IOException e){  
  43.                  e.printStackTrace();  
  44.                }  
  45.             }  
  46.               
  47.             if(out!=null)  
  48.             {  
  49.                try{  
  50.                    out.close();  
  51.                }catch(IOException e){  
  52.                    e.printStackTrace();  
  53.                 }  
  54.              }  
  55.          }  
  56.           
  57.   
  58.      }  
  59.   
  60.   
  61.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  62.             throws ServletException, IOException {  
  63.   
  64.       
  65.     }  
  66.   
  67. }  

 

注意:         try{...}  finally{...}

        如果 try{...} catch{...}  中沒有 catch{...},則必須要加上 finally{...}

        finally{...} 一般用來關閉流這些,不管有沒有異常,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM