欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-03-21 10:27:45|栏目:JAVA代码|点击:

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, 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();
    }

上一篇:Java源码解析HashMap简介

栏    目:JAVA代码

下一篇:Java中json使用方法_动力节点Java学院整理

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

本文地址:http://www.codeinn.net/misctech/84768.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有