【response-下载文件步骤】
Java中都通用文件下载(ContentType、文件头、response、out四步骤)
1.设置文件ContentType类型
2.设置文件头
3.通过response获取ServletOutputStream对象(out)
4.写到输出流(out)中
1 public void fileDownload(HttpServletResponse response){ 2 //获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载 3 String path = servletContext.getRealPath("/"); 4 5 //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 6 response.setContentType("multipart/form-data"); 7 //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf) 8 response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf"); 9 ServletOutputStream out; 10 //通过文件路径获得File对象(假如此路径中有一个download.pdf文件) 11 File file = new File(path + "download/" + "download.pdf"); 12 13 try { 14 FileInputStream inputStream = new FileInputStream(file); 15 16 //3.通过response获取ServletOutputStream对象(out) 17 out = response.getOutputStream(); 18 19 int b = 0; 20 byte[] buffer = new byte[512]; 21 while (b != -1){ 22 b = inputStream.read(buffer); 23 //4.写到输出流(out)中 24 out.write(buffer,0,b); 25 } 26 inputStream.close(); 27 out.close(); 28 out.flush(); 29 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } 33 }