第一步。網絡文件下載與從本地獲取是不一樣的,需要用URL類去打開連接從而獲得輸入流,其中path爲完整路徑包括http請求頭的,inputStream注意在程序的finally中關閉,如下代碼
/**
* 獲取外部文件流
*/
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403錯誤
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream=conn.getInputStream();
第二步。需要將獲得的輸入流輸出,輸出的話需要藉助response的outPutStream進行輸出,注意文件名如果帶有中文的話需要通過URLEncode.encode(filename,"UTF-8")進行轉碼
/**
* 輸出文件到瀏覽器
*/
int len=0;
// 輸出下載的響應頭,如果下載的文件是中文名,文件名需要經過url編碼
response.setContentType("text/html;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8"));
response.setHeader("Cache-Control", "no-cache");
out = response.getOutputStream();
while ((len = inputStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
第三步。關閉輸入輸出流
finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
LogUtil.warn(logger, "關閉讀取文件流出錯", e);
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
LogUtil.warn(logger, "關閉下載文件流出錯", e);
}
}
}
可能很多時候path完整路徑需要自己拼接,這個時候可以通過springmvc中的request獲得請求頭,其中注意io操作都要捕獲異常的,所以還需要try catch
String requestScheme= request.getScheme(); //請求協議http或則https