用java頁面下載圖片

來源:互聯網
上載者:User

標籤:

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頁面下載圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.