Java下载远程图片到本地服务器保存

置顶 精帖
0 4
大海无量
大海无量 博主 2020-12-11 23:36

 Java下载远程图片到本地服务器保存

有时候用爬虫采集图片,还是需要保存在本地的,有些网站做了限制,使用下面的方法来下载图片:

private String downloadPicture(String urlList) {

String imgurl = "";
URL url = null;
int imageNumber = 0;
try {
url = new URL(urlList);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
DataInputStream dataInputStream = new DataInputStream(url.openStream());
Attachment att = new Attachment();
String newName = String.valueOf(new Date().getTime()) + ".png";
String absoluteSavePath = imagePath + "/uploads/daohang/image" + getAvatarFoldername();
File file = new File(absoluteSavePath);
if (!file.exists()) {
file.mkdirs();
}
FileUtil.SaveFileFromInputStream(dataInputStream, absoluteSavePath, newName);
String path = "/uploads/daohang/image" + getAvatarFoldername() + "" + newName;
return path;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgurl;
}
回帖
  • 消灭零回复