根據(jù)URL下載圖片至客戶端、服務(wù)器的簡單實例
更新時間:2016年12月13日 09:28:52 投稿:jingxian
下面小編就為大家?guī)硪黄鶕?jù)URL下載圖片至客戶端、服務(wù)器的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
1、保存至服務(wù)器
根據(jù)路徑保存至項目所在服務(wù)器上。
String imgUrl="";//圖片地址
try {
// 構(gòu)造URL
URL url = new URL(imgUrl);
// 打開連接
URLConnection con = url.openConnection();
// 輸入流
InputStream is = con.getInputStream();
// 1K的數(shù)據(jù)緩沖
byte[] bs = new byte[1024];
// 讀取到的數(shù)據(jù)長度
int len;
// 輸出的文件流
OutputStream os = new FileOutputStream("c:\\image.jpg");//保存路徑
// 開始讀取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完畢,關(guān)閉所有鏈接
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2、保存至本地
以瀏覽器下載的方式保存至本地。
String imgUrl="";//URL地址
String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
URL url = new URL(imgUrl);
this.getServletResponse().setContentType("application/x-msdownload;");
this.getServletResponse().setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
this.getServletResponse().setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));
is = new BufferedInputStream(url.openStream());
os = new BufferedOutputStream(this.getServletResponse().getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
os.write(buff, 0, bytesRead);
}
if (is != null)
is.close();
if (os != null)
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
以上這篇根據(jù)URL下載圖片至客戶端、服務(wù)器的簡單實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
如果淘寶的七天自動確認收貨讓你設(shè)計你用Java怎么實現(xiàn)
在面試的時候如果面試官問淘寶的七天自動確認收貨讓你設(shè)計,你會怎么具體實現(xiàn)呢?跟著小編看一下下邊的實現(xiàn)過程,對大家的學習或工作具有一定的參考借鑒價值2021-09-09
使用springboot 獲取控制器參數(shù)的幾種方法小結(jié)
這篇文章主要介紹了使用springboot 獲取控制器參數(shù)的幾種方法小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

