檔案下載

放浪麴櫱發表於2020-10-07
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/FileServlet")
public class FileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        1、獲取下載檔案的路徑
        String realPath="H:\\Maven\\ServletTest\\Download\\src\\main\\resources\\天空.png";
        System.out.println(realPath);
//        2、下載的檔名是啥
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//        3、設定瀏覽器能夠支援下載的東西,中文檔名需要指定編碼方式,否則可能會亂碼
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));//分號改成冒號會展示圖片而不會下載
//        4、獲取下載檔案的輸入流
        FileInputStream in=new FileInputStream(realPath);
//        5、建立緩衝區
        int len=0;
        byte[] buffer=new byte[1024];
//        6、獲取outputStream物件
        ServletOutputStream out= response.getOutputStream();
//        7、將FileOutputStream流寫入buffer,使用outputStream將緩衝區資料輸出到客戶端
        while((len=in.read(buffer))>0)
        {
            out.write(buffer,0,len);
        }

        in.close();
        out.close();
    }
}