• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

根据URL下载图片至客户端、服务器的简单实例

java 搞代码 4年前 (2022-01-05) 29次浏览 已收录 0个评论

下面小编就为大家带来一篇根据URL下载图片至客户端、服务器的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

1、保存至服务器

根据路径保存至项目所在服务器上。

 String imgUrl="";//图片地址 try { // 构造URL URL url = new URL(imgUrl); // 打开连接 URLConnection con = url.openConnection(); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长<div style="color:transparent">来源gaodai.ma#com搞##代!^码@网</div>度 int len; // 输出的文件流 OutputStream os = new FileOutputStream("c:\\image.jpg-600");//保存路径 // 开始读取 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下载图片至客户端、服务器的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持gaodaima搞代码网

以上就是根据URL下载图片至客户端、服务器的简单实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:根据URL下载图片至客户端、服务器的简单实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址