欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-19 23:38:51
1 @RequestMapping("/downloadXls") 2 public void downloadXls(HttpServletRequest request, HttpServletResponse response) { 5 String contextPath = request... ......
 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     }