Java根据URL下载图片至客户端、服务器示例整合上传又拍云对象存储
侧边栏壁纸
  • 累计撰写 174 篇文章
  • 累计收到 1,068 条评论

Java根据URL下载图片至客户端、服务器示例整合上传又拍云对象存储

萧瑟
2022-01-08 / 1 评论 / 527 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月11日,已超过771天没有更新,若内容或图片失效,请留言反馈。

今天突然想起来做一个根据Url地址下载到又拍云中,调研顺便总结一下。

保存至服务器

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

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

保存至本地

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

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

保存到又拍云对象存储

根据又拍云SDK和上面的示例,整合了一下。

private static final String TEMP_PATH = "/temp";
/**
 * 互联网图片临时存入又拍云
 *
 * @param urlStr
 * @return 代理URL
 * @throws Exception
 */
public String downloadPicture(String urlStr) throws Exception {
    URL url = new URL(urlStr);
    InputStream fileInputStream = getInputStreamByUrl(urlStr);
    if (Objects.nonNull(inputStreamByUrl)) {
        RestManager manager = new RestManager("空间名称", "操作员名称", "操作员密码");
        Response result = manager.writeFile(TEMP_PATH + url.getFile(), fileInputStream, null);
        if (!result.isSuccessful()) {
            log.error("【又拍云】上传文件结果:{}", result);
            throw new UpException(String.valueOf(result.code()));
        }
        return upYunProp.getProxyUrl() + TEMP_PATH + url.getFile();
    }
    return null;
}
/**
 * 根据地址获得数据的输入流
 *
 * @param strUrl 网络连接地址
 * @return url的输入流
 */
private static InputStream getInputStreamByUrl(String strUrl) {
    HttpURLConnection conn = null;
    try {
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(20 * 1000);
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), output);
        return new ByteArrayInputStream(output.toByteArray());
    } catch (Exception e) {
        log.error(e + "");
    } finally {
        try {
            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception e) {
            log.error(e + "");
        }
    }
    return null;
}

效果图

参考示例

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

JAVA根据URL网址获取输入流-CSDN博客

评论 (1)

取消
  1. 头像
    珂泽
    河南省驻马店市 Windows 10 · Google Chrome

    收藏了,感觉迟早会用得到表情

    回复