servlet實現下載檔案
程式碼實現:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CodeReturn extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/jar");
ServletContext servletContext = getServletContext();
InputStream inputStream = servletContext.getResourceAsStream("/1.jar");
OutputStream outputStream = response.getOutputStream();
byte [] buff = new byte[1024];
int n = 0;
while((n = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, n);
}
outputStream.flush();
outputStream.close();
}
}
詳解:
通過Servlet下載1
被下載的資源必須放到WEB-INF目錄下(只要使用者不能通過瀏覽器直接訪問就OK),然後通過Servlet完成下載。
在jsp頁面中給出超連結,連結到DownloadServlet,並提供要下載的檔名稱。然後DownloadServlet獲取檔案的真實路徑,然後把檔案寫入到response.getOutputStream()流中。
download.jsp
<body> This is my JSP page. <br> <a href="<c:url value='/DownloadServlet?path=a.avi' <a href="<c:url value='/DownloadServlet?path=a.jpg'/>">a.jpg</a><br/> <a href="<c:url value='/DownloadServlet?path=a.txt'/>">a.txt</a><br/> </body> |
DownloadServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("path"); String filepath = this.getServletContext().getRealPath("/WEB-INF/uploads/" + filename); File file = new File(filepath); if(!file.exists()) { response.getWriter().print("您要下載的檔案不存在!"); return; } IOUtils.copy(new FileInputStream(file), response.getOutputStream()); } |
上面程式碼有如下問題:
l 可以下載a.avi,但在下載框中的檔名稱是DownloadServlet;
l 不能下載a.jpg和a.txt,而是在頁面中顯示它們。
通過Servlet下載2
下面來處理上一例中的問題,讓下載框中可以顯示正確的檔名稱,以及可以下載a.jpg和a.txt檔案。
通過新增content-disposition頭來處理上面問題。當設定了content-disposition頭後,瀏覽器就會彈出下載框。
而且還可以通過content-disposition頭來指定下載檔案的名稱!
String filename = request.getParameter("path"); String filepath = this.getServletContext().getRealPath("/WEB-INF/uploads/" + filename); File file = new File(filepath); if(!file.exists()) { response.getWriter().print("您要下載的檔案不存在!"); return; } response.addHeader("content-disposition", "attachment;filename=" + filename); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); |