/**
* 下载图片到本地
*
* @param downloadUrl 下载地址
* @return
*/
public List<String> downloadImage(String downloadUrl) {
DataInputStream in = null;
FileOutputStream out = null;
List<String> fileNameList = new ArrayList<>();
if (StringUtils.isBlank(downloadUrl)) {
return null;
}
String[] split = downloadUrl.split(",");
for (String s : split) {
try {
//获取宜搭临时免登地址
JSONObject jsonObject = YiDaUtils.getImageUrl(URLDecoder.decode(PERFIX + s, "UTF-8"));
if (jsonObject == null) {
throw new CustomException("宜搭返回链接为空!");
}
String result = jsonObject.getString("result");
log.info("宜搭图片返回的图片链接是====》::{}", result);
URL imageUrl = new URL(result);
in = new DataInputStream(imageUrl.openStream());
int len = 0;
byte[] buff = new byte[1024];
File file = new File("D:\\YiDaImage");
if (!file.exists()) {
file.mkdir();
}
String uuid = "\\" + UUID.randomUUID().toString().replace("-", "");
String fileName = file.getPath() + uuid + ".jpg";
out = new FileOutputStream(fileName);
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
//清空缓存区数据,确保读写操作都完成,再关闭流操作避免数据丢失
out.flush();
fileNameList.add(fileName);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null && out != null) {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return fileNameList;
}
/**
* 删除本地图片
*
* @param filePathList 本地路径
*/
public boolean deleteImage(List<String> filePathList) {
//导出之后删除阿里云存储的图片
// boolean flag = aliOssUtil.deleteOss(JSONObject.toJSONString(uploadImageUrlList));
// log.info("本级事件图片处理结果::{}", flag ? "阿里云图片删除成功" : "阿里云图片删除失败");
//删除文件夹
boolean flag = false;
if (CollectionUtils.isNotEmpty(filePathList)) {
filePathList.add(PATH);
for (String fileName : filePathList) {
File file = new File(fileName);
flag = file.delete();
}
}
return flag;
}
图片下载到本地工具类
最新推荐文章于 2024-07-21 22:27:18 发布