加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 14:39:29 所属栏目:Java 来源:网络整理
导读:1、保存至服务器 根据路径保存至项目所在服务器上。 String imgUrl="";//图片地址 try { // 构造URL URL url = new URL(imgUrl); // 打开连接 URLConnection con = url.openConnection(); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲

1、保存至服务器

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读