业务场景
系统中有些时候存储的图片是类似阿里云OSS的静态能访问的图片. 此时有需要把该图片下载
实现 :
package com.oms.service.external;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
public class FileDownloader {
/**
* 下载文件并保存到本地
*
* @param fileUrl 文件的URL
* @param savePath 本地保存路径
*/
public static void downloadFile(String fileUrl, String savePath) {
try {
URL url = new URL(fileUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000); // 连接超时时间
httpURLConnection.setReadTimeout(5000); // 读取超时时间
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream inputStream = httpURLConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(savePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("文件已成功下载并保存到: " + savePath);
}
} else {
System.err.println("无法下载文件,HTTP响应码: " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
System.err.println("下载文件时发生错误: " + e.getMessage());
}
}
/**
* 从URL中提取文件名
* @param url 完整的URL
* @return 文件名
*/
public static String extractFileNameFromUrl(String url) {
// 找到最后一个斜杠的位置
int lastSlashIndex = url.lastIndexOf('/');
if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
// 提取斜杠之后的部分
return url.substring(lastSlashIndex + 1);
}
return null; // 如果没有找到斜杠或斜杠是最后一个字符,则返回null
}
public static void main(String[] args) {
String fileUrl = "http://87.106.176.41:7777/upload/ups/b039c94b6534480087fdd300e80353e5.png";
String savePath = "D:\\QMDownload\\" + extractFileNameFromUrl(fileUrl);
downloadFile(fileUrl, savePath);
}
}