標籤:
try {
//根據String形式建立一個URL對象
String filePath = materialProductWorks.getDownloadImageUrl();
URL url = new URL(filePath);
//實列一個URLconnection對象,用來讀取和寫入此 URL 引用的資源
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//佈建要求方式為"GET"
conn.setRequestMethod("GET");
//逾時回應時間為5秒
conn.setConnectTimeout(5 * 1000);
//下載圖片重新命名,這行注掉
//String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
//擷取一個輸入資料流
InputStream is = conn.getInputStream();
// 清空buffer,設定頁面不緩衝
response.reset();
//使用戶端瀏覽器,區分不同種類的資料,並根據不同的MIME呼叫瀏覽器內不同的程式嵌入模組來處理相應的資料
response.setContentType("application/octet-stream");
//設定不同的名稱
String ufile = UUID.randomUUID().toString().replace("-", "");
//檔案下載,指定預設名
response.addHeader("Content-Disposition", "attachment;filename=" + ufile + ".png");
//一個byte[]數組,一次讀取多個位元組
byte[] bt = new byte[1000];
//用來接收每次讀取的位元組個數
int b = 0;
OutputStream out = response.getOutputStream();
//迴圈判斷,如果讀取的個數b為空白了,則is.read()方法返回-1,具體請參考InputStream的read();
while ((b = is.read(bt)) != -1) {
//將對象寫入到對應的檔案中
out.write(bt, 0, b);
}
//重新整理流
out.flush();
//關閉流
out.close();
is.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
用java頁面下載圖片