根据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         }
原文地址:https://www.cnblogs.com/pcheng/p/5550616.html