Java中都通用文件下載(ContentType、文件頭、response、out四步驟)


我們就直接切入主題啦,文件下載只需要四步:

1.設置文件ContentType類型

2.設置文件頭

3.通過response獲取ServletOutputStream對象(out)

4.寫到輸出流(out)中

 

下載代碼:

這里我使用的是SpringMVC,不過它在這里的唯一用途就是用來獲取ServletContext對象,這個對象的用途,下面實例中有說明

下載,需要用到兩個jar包:commons-fileupload.jar和commons-io.jar

 

Java代碼 復制代碼  收藏代碼
  1. import org.springframework.stereotype.Controller;   
  2. import org.springframework.web.bind.annotation.RequestMapping;   
  3. import org.springframework.web.context.ServletContextAware;   
  4.   
  5. import javax.servlet.ServletContext;   
  6. import javax.servlet.ServletOutputStream;   
  7. import javax.servlet.http.HttpServletResponse;   
  8. import java.io.*;   
  9.   
  10. @Controller  
  11. public class FileController implements ServletContextAware{   
  12.     //Spring這里是通過實現ServletContextAware接口來注入ServletContext對象   
  13.     private ServletContext servletContext;   
  14.   
  15.   
  16.     @RequestMapping("file/download")   
  17.     public void fileDownload(HttpServletResponse response){   
  18.         //獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載   
  19.         String path = servletContext.getRealPath("/");   
  20.   
  21.         //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型   
  22.         response.setContentType("multipart/form-data");   
  23.         //2.設置文件頭:最后一個參數是設置下載文件名(假如我們叫a.pdf)   
  24.         response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");   
  25.         ServletOutputStream out;   
  26.         //通過文件路徑獲得File對象(假如此路徑中有一個download.pdf文件)   
  27.         File file = new File(path + "download/" + "download.pdf");   
  28.   
  29.         try {   
  30.             FileInputStream inputStream = new FileInputStream(file);   
  31.   
  32.             //3.通過response獲取ServletOutputStream對象(out)   
  33.             out = response.getOutputStream();   
  34.   
  35.             int b = 0;   
  36.             byte[] buffer = new byte[512];   
  37.             while (b != -1){   
  38.                 b = inputStream.read(buffer);   
  39.                 //4.寫到輸出流(out)中   
  40.                 out.write(buffer,0,b);   
  41.             }   
  42.             inputStream.close();   
  43.             out.close();   
  44.             out.flush();   
  45.   
  46.         } catch (IOException e) {   
  47.             e.printStackTrace();   
  48.         }   
  49.     }   
  50.   
  51.     @Override  
  52.     public void setServletContext(ServletContext servletContext) {   
  53.         this.servletContext = servletContext;   
  54.     }   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM