今天突然想起来做一个根据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;
}
收藏了,感觉迟早会用得到