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


1、保存至服務器

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

 1         String imgUrl="";//圖片地址
 2         try {
 3             // 構造URL
 4             URL url = new URL(imgUrl);
 5             // 打開連接
 6             URLConnection con = url.openConnection();
 7             // 輸入流
 8             InputStream is = con.getInputStream();
 9             // 1K的數據緩沖
10             byte[] bs = new byte[1024];
11             // 讀取到的數據長度
12             int len;
13             // 輸出的文件流
14             OutputStream os = new FileOutputStream("c:\\image.jpg");//保存路徑
15             // 開始讀取
16             while ((len = is.read(bs)) != -1) {
17                 os.write(bs, 0, len);
18             }
19             // 完畢,關閉所有鏈接
20             os.close();
21             is.close();
22         } catch (MalformedURLException e) {
23             e.printStackTrace();
24         } catch (FileNotFoundException e) {
25             e.printStackTrace();
26         } catch (IOException e) {
27             e.printStackTrace();
28         }

 

2、保存至本地

  以瀏覽器下載的方式保存至本地。

 1         String imgUrl="";//URL地址
 2         String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
 3         BufferedInputStream is = null;
 4         BufferedOutputStream os = null;
 5         try {
 6             URL url = new URL(imgUrl);
 7             this.getServletResponse().setContentType("application/x-msdownload;");  
 8             this.getServletResponse().setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
 9             this.getServletResponse().setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));            
10             is = new BufferedInputStream(url.openStream());
11             os = new BufferedOutputStream(this.getServletResponse().getOutputStream());  
12             byte[] buff = new byte[2048];  
13             int bytesRead;  
14             while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {  
15                 os.write(buff, 0, bytesRead);  
16             }  
17             if (is != null)  
18                 is.close();  
19             if (os != null)  
20                 os.close();
21         } catch (MalformedURLException e) {
22             e.printStackTrace();
23         } catch (UnsupportedEncodingException e) {
24             e.printStackTrace();
25         } catch (IOException e) {
26             e.printStackTrace();
27         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM