根據(jù)URL下載圖片至客戶端、服務(wù)器的簡單實例
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)步驟解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08springboot+RabbitMQ+InfluxDB+Grafara監(jiān)控實踐
這篇文章主要介紹了springboot+RabbitMQ+InfluxDB+Grafara監(jiān)控實踐,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07深入淺析Netty 在 Dubbo 中是如何應(yīng)用的
國內(nèi)知名框架 Dubbo 底層使用的是 Netty 作為網(wǎng)絡(luò)通信,那么內(nèi)部到底是如何使用的呢?今天通過本文給大家詳細講解,對Netty 在 Dubbo中應(yīng)用相關(guān)知識感興趣的朋友跟隨小編一起看看吧2020-05-05SpringBoot?@InitBinder注解綁定請求參數(shù)的過程詳解
這篇文章主要介紹了SpringBoot?@InitBinder注解綁定請求參數(shù),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04idea設(shè)置@Author文件頭注釋的實現(xiàn)步驟
本文主要介紹了idea設(shè)置@Author文件頭注釋的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07