Java Web項目中實現檔案下載功能的執行個體教程_java

來源:互聯網
上載者:User

需求:實現一個具有檔案下載功能的網頁,主要下載壓縮包和圖片
兩種實現方法:

一:通過超連結實現下載
在HTML網頁中,通過超連結連結到要下載的檔案的地址

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>通過連結下載檔案</h1> <a href="/day06/download/cors.zip">壓縮包</a> <a href="/day06/download/1.png">圖片</a> </body> </html> 

其中day06/download是文檔路徑,本執行個體的程式結構如下:

程式運行後,可以通過單擊需要下載文檔實現下載

但是這裡會出現一個問題,就是單擊下載壓縮包的時候會彈出下載頁面,但是下載圖片的時候瀏覽器就直接開啟了圖片,沒有下載。

這是因為通過超連結下載檔案時,如果瀏覽器可以識別該檔案格式,瀏覽器就會直接開啟。只有瀏覽器不能識別該檔案格式的時候,才會實現下載。因此利用第二種方法實現下載功能。

二:通過Servlet程式實現下載
通過Servlet下載檔案的原理是通過servlet讀取目標程式,將資源返回用戶端。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>通過連結下載檔案</h1> <a href="/day06/download/cors.zip">壓縮包</a> <a href="/day06/download/1.png">圖片</a> <h1>通過servlet程式下載檔案</h1> <a href="/day06/ServletDownload?filename=cors.zip">壓縮包</a> <a href="/day06/ServletDownload?filename=1.png">圖片</a> </body> </html> 

其中,/day06/ServletDownload 是servlet程式的映射路徑
然後建立一個servlet,名稱為ServletDownload,URL映射為/ServletDownload

添加代碼如下:

package com.lsgjzhuwei.servlet.response;  import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  /**  * Servlet implementation class ServletDownload  */ @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" }) public class ServletDownload extends HttpServlet {   private static final long serialVersionUID = 1L;        /**    * @see HttpServlet#HttpServlet()    */   public ServletDownload() {     super();     // TODO Auto-generated constructor stub   }    /**    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)    */   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {     // TODO Auto-generated method stub          //獲得請求檔案名稱     String filename = request.getParameter("filename");     System.out.println(filename);          //設定檔案MIME類型     response.setContentType(getServletContext().getMimeType(filename));     //設定Content-Disposition     response.setHeader("Content-Disposition", "attachment;filename="+filename);     //讀取目標檔案,通過response將目標檔案寫到用戶端     //擷取目標檔案的絕對路徑     String fullFileName = getServletContext().getRealPath("/download/" + filename);     //System.out.println(fullFileName);     //讀取檔案     InputStream in = new FileInputStream(fullFileName);     OutputStream out = response.getOutputStream();          //寫檔案     int b;     while((b=in.read())!= -1)     {       out.write(b);     }          in.close();     out.close();   }    /**    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)    */   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {     // TODO Auto-generated method stub   }  } 

重啟tomcat伺服器,即可實現對壓縮包和對圖片的下載。

三、小技巧:
點選連結來下載檔案的方式很簡便,後台把檔案流輸出來,通過瀏覽器實現下載功能,包括詢問位置與檔案存放,大多數瀏覽器會配置一個固定位置,不一定每次都問。

前端就非常簡單了,一個<a>標籤,href=“後台方法地址”,如果你的需求不能直接用超連結方式,可以在js裡寫 window.location.href =“後台方法地址”。

這樣跳轉到後台方法後

String filePath = this.getClass().getClassLoader().getResource("").toURI().getPath()          + "/exportPdf.pdf"; //檔案在項目中的路徑    File outfile = new File(filePath);    String filename = outfile.getName();// 擷取檔案名稱    InputStream fis = new BufferedInputStream(new FileInputStream(          filePath));    byte[] buffer = new byte[fis.available()];     fis.read(buffer); //讀取檔案流    fis.close();    response.reset(); //重設結果集    response.addHeader("Content-Disposition", "attachment;filename="        + new String(filename.replaceAll(" ", "").getBytes("utf-8"),        "iso8859-1")); //返回頭 檔案名稱    response.addHeader("Content-Length", "" + outfile.length()); //返回頭 檔案大小    response.setContentType("application/octet-stream");  //設定資料種類    //擷取返回體輸出權    OutputStream os = new BufferedOutputStream(response.getOutputStream());     os.write(buffer); // 輸出檔案    os.flush();    os.close();

瀏覽器會直接識別這種形式的檔案輸出,彈出對話方塊。
注意此方法一定要用連結方式調後台,使用ajax和XMLHttpRequest方式都是不行的,這樣返回的檔案流會返回到方法的回呼函數中,當然如果你想在js中擷取檔案,這樣也行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.