java实现文件下载 调用IE自带的下载工具来完成下载

/**
  * @author 
  * May 7, 2013 1:56:03 PM
  * @param path 下载文件的全路径(包括文件名)
  * @param response
  * @throws FileNullException 自定义异常,当前文件不存在的时候抛出此异常
  * @throws IOException
  */
 public static void download(String path, HttpServletResponse response) throws FileNullException, IOException {
  OutputStream toClient = null;
  InputStream bis = null;
  FileInputStream fis = null;
  // path是指欲下载的文件的路径。
  File file = new File(path);
  //判断当前文件是否存在,若是不存在则跑出异常
  if(!file.exists()) {
   throw new FileNullException("下载失败,该文件不存在,可能已经被删除");
  }
  // 取得文件名。
  String filename = file.getName();
  // 以流的形式下载文件。
  fis = new FileInputStream(path);
  bis = new BufferedInputStream(fis);
  byte[] buffer = new byte[bis.available()];
  fis.read(buffer);
  fis.close();
  bis.close();
  // 清空response
  response.reset();
  // 设置response的Header
  response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
  response.addHeader("Content-Length", "" + file.length());
  toClient = new BufferedOutputStream(response.getOutputStream());
  response.setContentType("application/octet-stream");
  toClient.flush();
  toClient.write(buffer);
  toClient.close();
 }

注意事项:我这里并没有抓取异常信息,而是将异常信息抛向了调用方(action)中,在action中进行了除了。FileNullException自定义异常,主要是用来抛出文件不存在的信息,用于在页面提示用户。当然也可以有其他处理方式,可自行实现。

由于csdn上传资源功能有问题,导致经常无法上传,顾我将不上传源代码。有意者可以留言索要。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值