java實現檔案下載 調用IE內建的下載工具來完成下載

來源:互聯網
上載者:User

/**
  * @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上傳資源功能有問題,導致經常無法上傳,顧我將不上傳原始碼。有意者可以留言索要。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.