当前位置: 移动技术网 > IT编程>开发语言>Java > [功能集锦] 001 - java下载文件

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

2019年06月21日  | 移动技术网IT编程  | 我要评论
 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     }

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网