一般來說文件下載需要的步驟為:
(1)獲得客戶端請求的文件的名稱
String fileName = req.getParameter("fileName");
(2)獲得服務器端的真實的物理路徑
File dir = new File(super.getServletContext().getRealPath("/temp"));
(3)創建目標文件的輸入流對象
File targetFile = new File(dir, fileName);
(4) 執行下載
<1>設置返回內容的類型
resp.setContentType("application/msword");//Content-Type
<2>設置返回內容的長度
resp.setContentLength((int)targetFile.length());//Content-Length
<3>設置怎樣處理文件,征求客戶的意見
resp.setHeader("Content-Disposition","attachment;filename=test.doc");
<4>利用tomcat的FileUtils.copyFile方法進行文件的下載
FileUtils.copyFile(targetFile, resp.getOutputStream());
FileDownloadServlet.java
package com.xixi.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
@WebServlet(urlPatterns="/downloadServlet")
public class FileDownoloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設置字符編碼
req.setCharacterEncoding("utf-8");
//獲得請求的fileName的名稱
String fileName = req.getParameter("fileName");
if (fileName!=null && fileName.length() > 0) {
//獲得服務器端的真實的物理路徑
File dir = new File(super.getServletContext().getRealPath("/temp"));
File targetFile = new File(dir, fileName);
if (targetFile.exists()) {
//執行下載
//設置返回內容的類型
resp.setContentType("application/msword");//Content-Type
//設置返回內容的長度
resp.setContentLength((int)targetFile.length());//Content-Length
//設置怎樣處理文件,征求客戶的意見
resp.setHeader("Content-Disposition", "attachment;filename=test.doc");
//利用tomcat的FileUtils.copyFile方法進行文件的下載
FileUtils.copyFile(targetFile, resp.getOutputStream());
}
}
}
}