国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

根據URL下載圖片至客戶端、服務器的簡單實例

2019-11-26 13:27:13
字體:
來源:轉載
供稿:網友

1、保存至服務器

根據路徑保存至項目所在服務器上。

String imgUrl="";//圖片地址    try {      // 構造URL      URL url = new URL(imgUrl);      // 打開連接      URLConnection con = url.openConnection();      // 輸入流      InputStream is = con.getInputStream();      // 1K的數據緩沖      byte[] bs = new byte[1024];      // 讀取到的數據長度      int len;      // 輸出的文件流      OutputStream os = new FileOutputStream("c://image.jpg");//保存路徑      // 開始讀取      while ((len = is.read(bs)) != -1) {        os.write(bs, 0, len);      }      // 完畢,關閉所有鏈接      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();    }

以上這篇根據URL下載圖片至客戶端、服務器的簡單實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 米泉市| 博罗县| 八宿县| 义马市| 亳州市| 连云港市| 德阳市| 宁陵县| 棋牌| 北碚区| 清徐县| 开化县| 社旗县| 临海市| 岗巴县| 靖州| 峨眉山市| 宁德市| 石景山区| 犍为县| 和龙市| 台北县| 临澧县| 巴彦淖尔市| 炎陵县| 怀安县| 即墨市| 长汀县| 青田县| 南靖县| 上饶县| 绩溪县| 衡水市| 甘肃省| 漾濞| 江孜县| 乐亭县| 丹寨县| 陵川县| 全州县| 寿阳县|