编程语言
首页 > 编程语言> > [功能集锦] 001 - java下载文件

[功能集锦] 001 - java下载文件

作者:互联网

 1     @RequestMapping("/downloadXls")
 2     public void downloadXls(HttpServletRequest request, HttpServletResponse response) { 5         String contextPath = request.getSession().getServletContext().getRealPath(File.separator + "report");
 6         String excelName = xxxxxxxxx;
 7         String excelFullName = contextPath + File.separator + excelName + ".xls";
 8         InputStream inStream = null, fileInStream = null;
 9         ServletOutputStream outStream = null;
10         int byteRead;
11         try {
12             fileInStream = new FileInputStream(excelFullName);
13             inStream = new BufferedInputStream(fileInStream);
14             response.reset();
15             response.setContentType("APPLICATION/OCTET-STREAM");
16             response.setHeader("Content-disposition", "attachment; filename=" + excelName + ".xls");
17             outStream = response.getOutputStream();
18             byte[] buffer = new byte[1024];
19             while ((byteRead = inStream.read(buffer)) != -1) {
20                 outStream.write(buffer, 0, byteRead);
21             }
22             response.flushBuffer();
23             fileInStream.close();
24             inStream.close();
25             outStream.close();
26         } catch (Exception e) {
27             LOGGER.error(e);
28         }finally{
29             try {
30                 if(fileInStream!=null){
31                     fileInStream.close();
32                 }
33                 if(inStream!=null){
34                     inStream.close();
35                 }
36                 if(outStream!=null){
37                     outStream.close();
38                 }
39             } catch (IOException e2) {
40                 LOGGER.error(e2);
41             }
42         }
43     }

 

标签:java,fileInStream,outStream,response,001,集锦,close,null,inStream
来源: https://www.cnblogs.com/ruanian/p/11060227.html