Response下載檔案

冰天!發表於2024-07-21

1.首先在maven專案下建立java class 類 ,然後繼承HttpServlet介面。 重寫doGet方法。
2.程式碼如下

點選檢視程式碼
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class response extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.獲取檔案下載路徑
       // String realPath = this.getServletContext().getRealPath("/1.png");
        String realPath="F:\\demo\\maven01\\response01\\target\\classes\\1.png";
        //2.下載檔案命是啥
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3.設定想辦法讓瀏覽器能夠(Content-Disposition)支援下載我們需要的東西
        resp.setHeader("Content-Disposition","attachment;filename="+filename);
        //4.獲取下載檔案的輸入流
        FileInputStream in = new FileInputStream(realPath);
        //5.建立緩衝區
        int len=0;
        byte[] buffer = new byte[1024];
        //6.獲取OutputStream 物件
        ServletOutputStream out = resp.getOutputStream();
        //7.將FileOutputStream 流寫入buffer緩衝區
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }
}
3.執行成功會自動下載 ![](https://img2024.cnblogs.com/blog/2906065/202407/2906065-20240721223448694-1725371143.png)

相關文章