根據(jù)URL下載圖片至客戶端、服務(wù)器的簡(jiǎn)單實(shí)例
1、保存至服務(wù)器
根據(jù)路徑保存至項(xiàng)目所在服務(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ù)長(zhǎng)度
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ù)器的簡(jiǎn)單實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
如果淘寶的七天自動(dòng)確認(rèn)收貨讓你設(shè)計(jì)你用Java怎么實(shí)現(xiàn)
在面試的時(shí)候如果面試官問(wèn)淘寶的七天自動(dòng)確認(rèn)收貨讓你設(shè)計(jì),你會(huì)怎么具體實(shí)現(xiàn)呢?跟著小編看一下下邊的實(shí)現(xiàn)過(guò)程,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值2021-09-09
使用springboot 獲取控制器參數(shù)的幾種方法小結(jié)
這篇文章主要介紹了使用springboot 獲取控制器參數(shù)的幾種方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
java實(shí)現(xiàn)簡(jiǎn)易飛機(jī)大戰(zhàn)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)易飛機(jī)大戰(zhàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
springboot實(shí)現(xiàn)讀取nacos配置文件
這篇文章主要介紹了springboot實(shí)現(xiàn)讀取nacos配置文件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Maven統(tǒng)一版本管理的實(shí)現(xiàn)
在使用Maven多模塊結(jié)構(gòu)工程時(shí),配置版本是一個(gè)比較頭疼的事,本文主要介紹了Maven統(tǒng)一版本管理的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03

