是否存在返回值根据自己的情况定义
private List<Structure> saveFile(List<Structure> files) {
List<Structure> results = new ArrayList<>();
if (com.alibaba.nacos.common.utils.CollectionUtils.isNotEmpty(files)) {
for (Structure file : files) {
Structure structure = new Structure();
results.add(structure);
structure.setFileName(file.getFileName());
structure.setFileDescription("fileId");
structure.setFileSize(file.getFileSize());
// 替换为你想要保存的路径和文件名
String savePath = "D:\\lu\\save\\" + file.getFileName();
try {
//下载图片并保存
URL url = new URL(file.getFilePath());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
System.out.println("Image downloaded and saved to " + savePath);
//开始上传服务器
File photo = new File(savePath);
byte[] photoBytes = new byte[(int) photo.length()];
try (FileInputStream fis = new FileInputStream(photo);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
int bytesRead;
while ((bytesRead = fis.read(photoBytes)) != -1) {
bos.write(photoBytes, 0, bytesRead);
}
//这里根据自己的上传接口参数进行操作
String upload =
MinioUtils.upload(
new ByteArrayInputStream(bos.toByteArray()),
...
file.getFileName());
if (upload != null) {
//如果有返回值代表上传成功,根据自己的上传接口返回值进行判断
System.out.println(upload);
//根据自己的文件访问参数设置存入参数
structure.setFilePath(upload);
// 删除本地照片文件
photo.delete();
System.out.println("Photo deleted after successful upload.");
} else {
System.out.println("Failed to upload photo.");
}
}
} else {
System.out.println(
"Image download failed with response code " + connection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//这一步可以直接存入数据,也可作为file字段的处理方法
return results;
}