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

时间:2021-10-23 23:07:26

1、保存至服务器

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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、保存至本地

以浏览器下载的方式保存至本地。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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下载图片客户端、服务器的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。