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