我們就直接切入主題啦,文件下載只需要四步:
1.設(shè)置文件ContentType類型
2.設(shè)置文件頭
3.通過response獲取ServletOutputStream對象(out)
4.寫到輸出流(out)中
下載代碼:
這里我使用的是SpringMVC,,不過它在這里的唯一用途就是用來獲取ServletContext對象,,這個對象的用途,下面實例中有說明
下載,,需要用到兩個jar包:commons-fileupload.jar和commons-io.jar
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.context.ServletContextAware;
-
- import javax.servlet.ServletContext;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletResponse;
- import java.io.*;
-
- @Controller
- public class FileController implements ServletContextAware{
- //Spring這里是通過實現(xiàn)ServletContextAware接口來注入ServletContext對象
- private ServletContext servletContext;
-
-
- @RequestMapping("file/download")
- public void fileDownload(HttpServletResponse response){
- //獲取網(wǎng)站部署路徑(通過ServletContext對象),用于確定下載文件位置,,從而實現(xiàn)下載
- String path = servletContext.getRealPath("/");
-
- //1.設(shè)置文件ContentType類型,,這樣設(shè)置,會自動判斷下載文件類型
- response.setContentType("multipart/form-data");
- //2.設(shè)置文件頭:最后一個參數(shù)是設(shè)置下載文件名(假如我們叫a.pdf)
- response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");
- ServletOutputStream out;
- //通過文件路徑獲得File對象(假如此路徑中有一個download.pdf文件)
- File file = new File(path + "download/" + "download.pdf");
-
- try {
- FileInputStream inputStream = new FileInputStream(file);
-
- //3.通過response獲取ServletOutputStream對象(out)
- out = response.getOutputStream();
-
- int b = 0;
- byte[] buffer = new byte[512];
- while (b != -1){
- b = inputStream.read(buffer);
- //4.寫到輸出流(out)中
- out.write(buffer,0,b);
- }
- inputStream.close();
- out.close();
- out.flush();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
- }
|