java web response提供文件下載功能
阿新 • • 發佈:2018-01-18
http check cep oca clu django throws att static
webapp項目的結構如下圖:
download.html文件的內容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>資源下載:</h1>
<p> 單純地使用a標簽時,只有瀏覽器不能解析的文件才會是下載,否則將被瀏覽器直接解析。</p>
<a href="/WEB/resource/a.mp3" >a.mp3</a><br>
<a href="/WEB/resource/a.exe" >a.exe</a><br>
<a href="/WEB/resource/a.txt" >a.txt</a><br>
<a href="/WEB/resource/a.xlsx" >a.xlsx</a><br>
<a href="/WEB/resource/a.png" > a.png</a><br>
<p>因此,使用a標簽結合servlet的response指示瀏覽器不解析這些待下載文件</p>
<a href="/WEB/download?filename=a.mp3" >a.mp3</a><br>
<a href="/WEB/download?filename=a.exe" >a.exe</a><br>
<a href="/WEB/download?filename=a.txt" >a.txt</a><br>
<a href="/WEB/download?filename=a.xlsx" >a.xlsx</a><br>
<a href="/WEB/download?filename=a.png" >a.png</a><br>
</body>
</html>
負責處理下載的Servlet——download.java文件的內容如下:
package com.download.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Download
*/
public class Download extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.獲取請求下載的文件名
String filename = request.getParameter("filename");
//2.獲取文件的文件系統路徑
String filePath = request.getServletContext().getRealPath("resource/"+filename);
//3.設置響應頭,提示瀏覽器不要解析響應的文件數據,而是以附件(attachment)的形式解析,即下載功能
response.setContentType(this.getServletContext().getMimeType(filename));
response.setHeader("Content-Disposition", "attachment;filename="+filename);
//4.讀取文件的 輸入流,以及響應的輸出流,並將數據輸出給客戶端
InputStream in = new FileInputStream(filePath);
ServletOutputStream out = response.getOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))!=-1) {
out.write(buf, 0, len);
}
in.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
在瀏覽器地址欄中輸入http://localhost:8080/DownloadServlet/download.html
。
註:若您覺得這篇文章還不錯請點擊右下角推薦,您的支持能激發作者更大的寫作熱情,非常感謝!
java web response提供文件下載功能