根据图片URL地址下载到本地

public static void main(String[] args) {
String replace = "https://betapic.uhomecp.com/service/2020/12/09/843/202012091938511177_734_743.JPEG";
String tempDirectoryPath = "/home/si/apache-tomcat-8.0.32/webapps/tempPath/";
String[] split = replace.split("/");
try {
URL url = new URL(replace);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
File file = new File( tempDirectoryPath+"/"+split[split.length-1]);
System.out.println(file);
FileItemFactory factory = new DiskFileItemFactory(16, null);//image/jpeg:jpg
FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
int bytesRead = 0;
byte[] buffer1 = new byte[8192];
// 下载文件到一个指定地方
FileUtils.copyURLToFile(url, file);
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer1, 0, 8192)) != -1) {
os.write(buffer1, 0, bytesRead);
}
MultipartFile multipartFile = new CommonsMultipartFile(item);
System.out.println("4.multipartFile.getName----------图片文件"+multipartFile.getName());
os.close();
fis.close();
inputStream.close();
if (file.exists()){
if (file.isFile()){
FileUtils.deleteQuietly(file);
}

}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
posted @ 2020-12-11 10:41  小梦想大实现  阅读(685)  评论(0编辑  收藏  举报