根據(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)文章
Java web spring異步方法實現(xiàn)步驟解析
這篇文章主要介紹了Java web spring異步方法實現(xiàn)步驟解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08
springboot+RabbitMQ+InfluxDB+Grafara監(jiān)控實踐
這篇文章主要介紹了springboot+RabbitMQ+InfluxDB+Grafara監(jiān)控實踐,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
SpringBoot?@InitBinder注解綁定請求參數(shù)的過程詳解
這篇文章主要介紹了SpringBoot?@InitBinder注解綁定請求參數(shù),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
idea設(shè)置@Author文件頭注釋的實現(xiàn)步驟
本文主要介紹了idea設(shè)置@Author文件頭注釋的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07

