1. 程式人生 > 其它 >Servlet學習——HttpServletResponse下載檔案

Servlet學習——HttpServletResponse下載檔案

技術標籤:java

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1. 要獲取下載檔案的路徑
        String realPath = "D:\\idea_workspace\\webapp-maven\\response-test\\src\\main\\resources\\1.png";
        System.out.
println("下載檔案的路徑:"+realPath); //2. 下載的檔名 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); //3. 設定想辦法讓瀏覽器能夠支援下載我們需要的東西(Content-Disposition),中文檔名URLEncoder.encode編碼,否則有可能亂碼 resp.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 = resp.getOutputStream(); //7. 將FileOutputStream流寫入到buffer緩衝區
//8. 使用OutputStream將緩衝區中的資料輸出到客戶端! while ((len=in.read(buffer))>0){ out.write(buffer,0,len); } in.close(); out.close(); }