Java Web項(xiàng)目中實(shí)現(xiàn)文件下載功能的實(shí)例教程
需求:實(shí)現(xiàn)一個(gè)具有文件下載功能的網(wǎng)頁,主要下載壓縮包和圖片
兩種實(shí)現(xiàn)方法:
一:通過超鏈接實(shí)現(xiàn)下載
在HTML網(wǎng)頁中,通過超鏈接鏈接到要下載的文件的地址
<!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是文檔路徑,本實(shí)例的程序結(jié)構(gòu)如下:

程序運(yùn)行后,可以通過單擊需要下載文檔實(shí)現(xiàn)下載

但是這里會(huì)出現(xiàn)一個(gè)問題,就是單擊下載壓縮包的時(shí)候會(huì)彈出下載頁面,但是下載圖片的時(shí)候?yàn)g覽器就直接打開了圖片,沒有下載。

這是因?yàn)橥ㄟ^超鏈接下載文件時(shí),如果瀏覽器可以識(shí)別該文件格式,瀏覽器就會(huì)直接打開。只有瀏覽器不能識(shí)別該文件格式的時(shí)候,才會(huì)實(shí)現(xiàn)下載。因此利用第二種方法實(shí)現(xiàn)下載功能。
二:通過Servlet程序?qū)崿F(xiàn)下載
通過Servlet下載文件的原理是通過servlet讀取目標(biāo)程序,將資源返回客戶端。
<!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程序的映射路徑
然后新建一個(gè)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);
//設(shè)置文件MIME類型
response.setContentType(getServletContext().getMimeType(filename));
//設(shè)置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+filename);
//讀取目標(biāo)文件,通過response將目標(biāo)文件寫到客戶端
//獲取目標(biāo)文件的絕對路徑
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服務(wù)器,即可實(shí)現(xiàn)對壓縮包和對圖片的下載。


三、小技巧:
點(diǎn)擊鏈接來下載文件的方式很簡便,后臺(tái)把文件流輸出來,通過瀏覽器實(shí)現(xiàn)下載功能,包括詢問位置與文件存放,大多數(shù)瀏覽器會(huì)配置一個(gè)固定位置,不一定每次都問。
前端就非常簡單了,一個(gè)<a>標(biāo)簽,href=“后臺(tái)方法地址”,如果你的需求不能直接用超鏈接方式,可以在js里寫 window.location.href =“后臺(tái)方法地址”。
這樣跳轉(zhuǎn)到后臺(tái)方法后
String filePath = this.getClass().getClassLoader().getResource("").toURI().getPath()
+ "/exportPdf.pdf"; //文件在項(xiàng)目中的路徑
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(); //重置結(jié)果集
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"); //設(shè)置數(shù)據(jù)種類
//獲取返回體輸出權(quán)
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer); // 輸出文件
os.flush();
os.close();
瀏覽器會(huì)直接識(shí)別這種形式的文件輸出,彈出對話框。
注意此方法一定要用鏈接方式調(diào)后臺(tái),使用ajax和XMLHttpRequest方式都是不行的,這樣返回的文件流會(huì)返回到方法的回調(diào)函數(shù)中,當(dāng)然如果你想在js中獲取文件,這樣也行。
- java實(shí)現(xiàn)FTP文件上傳與文件下載
- java web項(xiàng)目實(shí)現(xiàn)文件下載實(shí)例代碼
- 詳解Java文件下載的幾種實(shí)現(xiàn)方式
- java使用http實(shí)現(xiàn)文件下載學(xué)習(xí)示例
- Java Web實(shí)現(xiàn)文件下載和亂碼處理方法
- JavaEE實(shí)現(xiàn)文件下載
- Java Web端程序?qū)崿F(xiàn)文件下載的方法分享
- Java實(shí)現(xiàn)ftp文件上傳下載解決慢中文亂碼多個(gè)文件下載等問題
- javaweb 實(shí)現(xiàn)文件下載的方法及實(shí)例代碼
- java實(shí)現(xiàn)文件下載的兩種方式
相關(guān)文章
springboot整合RabbitMQ中死信隊(duì)列的實(shí)現(xiàn)
死信是無法被消費(fèi)的消息,產(chǎn)生原因包括消息TTL過期、隊(duì)列最大長度達(dá)到以及消息被拒絕且不重新排隊(duì),RabbitMQ的死信隊(duì)列機(jī)制能夠有效防止消息數(shù)據(jù)丟失,適用于訂單業(yè)務(wù)等場景,本文就來介紹一下2024-10-10
Java實(shí)現(xiàn)文件監(jiān)控器FileMonitor的實(shí)例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)文件監(jiān)控器FileMonitor的實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
SpringBoot整合GitLab-CI實(shí)現(xiàn)持續(xù)集成的過程
這篇文章主要介紹了SpringBoot整合GitLab-CI實(shí)現(xiàn)持續(xù)集成,本文詳細(xì)講述了 GitLab-CI 持續(xù)集成的安裝、部署、以及配置,需要的朋友可以參考下2022-12-12

