文件下載用servlet實現

一般來說文件下載需要的步驟為:

(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());
            }
        }
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容