JAVA下载的返回值

      在执行 write写入流到一定字节时会弹出下载对话框,当client端点击打开或是保存时,这时候会返回 true值,如果点击取消则返回IOException false,以此来判断客户端打开完之后执行的操作,特别注意的是当client端执行打开,保存,取消操作时会再次调用进入下载方法的Action,以此来结束所构建的流的状态,刚开始不知道什么原因,后来单步执行,才发现,不过有个问题就是,如果文件比较小,,只会执行一次.
    对于构建输出流的时候要注意在适当的位置构建,不然在关闭的时候调用close()方法无法关闭输出流,将会导致该进程一致被占用.
java 代码
  1. public boolean downloadFile(HttpServletResponse response, String urlPath) {   
  2.         boolean isSuccess = true;   
  3.         String dst_fname = urlPath.substring(urlPath.lastIndexOf("\\") + 1);  
  4.         try {  
  5.             dst_fname = URLEncoder.encode(dst_fname, "utf-8");  
  6.         } catch (UnsupportedEncodingException e2) {  
  7.         }  
  8.         FileInputStream fis = null;  
  9.         BufferedInputStream bis=null;  
  10.         OutputStream os=null;  
  11.         BufferedOutputStream bos=null;  
  12.         try {  
  13.             response.reset();  
  14.             response.setContentType("application/x-download");  
  15.             response.setHeader("Content-disposition", "attachment; filename=\""  
  16.                     + dst_fname + "\"");   
  17.   
  18.             fis = new FileInputStream(urlPath);   
  19.   
  20.             bis = new BufferedInputStream(fis);   
  21.             os = response.getOutputStream();   
  22.             bos = new BufferedOutputStream(os);   
  23.             byte[] buf = new byte[1024];   
  24.             int i = -1;   
  25.             while ((i = bis.read(buf)) != -1) {   
  26.                 bos.write(buf, 0, i);   
  27.             }   
  28.             bos.flush();   
  29.         } catch (IOException e) {   
  30.             isSuccess = false;   
  31.         } catch (Exception e) {   
  32.             isSuccess = false;   
  33.         } finally {   
  34.             try {   
  35.                 if (bos != null) {   
  36.                     bos.close();   
  37.                     bos=null;   
  38.                 }   
  39.                 if (os != null) {   
  40.                     os.close();   
  41.                     os=null;   
  42.                 }   
  43.                 if (bis != null) {   
  44.                     bis.close();   
  45.                     bis=null;   
  46.                 }   
  47.                 if(fis!=null){   
  48.                     fis.close();   
  49.                     fis=null;   
  50.                 }   
  51.             } catch (IOException e) {   
  52.                 isSuccess = false;   
  53.             }   
  54.         }   
  55.            
  56.         return isSuccess;   
  57.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值