String imageUrl = data.get("results"); //需要下载的图片URL
String typeName = data.get("typeName"); // 要保存图片的文件名
try {
String uuid = UUID.randomUUID().toString();
File dir = new File(shpOrExcelPath, "screenshot");
if(!dir.exists()) {
if (!dir.mkdirs()) {
return Result.fail(MKDIR_FAILED_CODE, MKDIR_FAILED_MESSAGE);
}
}
// 打开连接
URL url = new URL(imageUrl);
URLConnection connection = url.openConnection();
// 设置请求超时为15秒
connection.setConnectTimeout(15 * 1000);
// 读取数据流并保存到本地
InputStream input = connection.getInputStream();
byte[] datas = new byte[2048];
int len;
FileOutputStream output = new FileOutputStream(new File(dir, typeName + ".jpg"));
while ((len = input.read(datas)) != -1) {
output.write(datas, 0, len);
}
output.close();
input.close();
System.out.println("图片保存成功:" + dir + typeName + ".jpg");
} catch (IOException e) {
System.out.println("图片保存失败:" + e.getMessage());
}
finally {
}