根据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 }
本文来自博客园,作者:PC君,转载请注明原文链接:https://www.cnblogs.com/pcheng/p/5550616.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)