Java從伺服器下載檔案到本地
阿新 • • 發佈:2018-11-10
我的需求是從伺服器端的某磁碟中獲取amr檔案,並下載。
首先傳遞的引數strUrl為物理路徑,是絕對路徑。
//獲取檔名,此處看個人如何設計的
String filename = strUrl.substring(strUrl.lastIndexOf("/")+1);
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
String path = strUrl;
File file = new File(path);
//如果檔案不存在
if(!file.exists()){
return false;
}
//設定響應頭,控制瀏覽器下載該檔案
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//讀取要下載的檔案,儲存到檔案輸入流
FileInputStream in = new FileInputStream(path);
//建立輸出流
OutputStream out = response.getOutputStream();
//快取區
byte buffer[] = new byte[1024];
int len = 0;
//迴圈將輸入流中的內容讀取到緩衝區中
while((len = in .read(buffer)) > 0){
out.write(buffer, 0, len);
}
//關閉
in.close();
out.close();
其次,瀏覽器端在發起請求時,要使用href指向,如:
window.location.href=’//介面名稱’,或<a href='/*介面名稱*/'></a>