I need to upload multiple files to S3, but don't need to store this files because over time, a lot of files will accumulate. I need to convert this files from MultipartFiles I'm trying to use temp files for safe. I have such methods
public void uploadFilesToS3(Map<FileS3, MultipartFile> myFileMap) {
TransferManager transferManager = TransferManagerBuilder.standard()
.withS3Client(s3Client)
.build();
try {
List<File> fileList = createTempFilesFromInputStreams(myFileMap);
MultipleFileUpload multipleFileUpload = transferManager.uploadFileList(awsProperties.getBucket(), S3Package.MY_PACKEGE.getValue(), new File("."), fileList);
multipleFileUpload.waitForCompletion();
} catch (Exception e) {
log.error("Couldn't upload list of files to AWS S3");
throw new RuntimeException(e);
}
}
Convert Multipart files to Files
private List<File> createTempFilesFromInputStreams(Map<FileS3, MultipartFile> resumeFileMap) {
List<File> tempFiles = new ArrayList<>();
resumeFileMap.forEach((fileS3, multipartFile) -> {
try (InputStream inputStream = multipartFile.getInputStream()) {
File tempFile = File.createTempFile(fileS3.getName(), "." + fileS3.getExtension());
File renamedFile = new File(tempFile.getParent(), fileS3.getFullName());
if (tempFile.renameTo(renamedFile)) {
tempFiles.add(renamedFile);
} else {
throw new IOException("Failed to rename temp file to desired name");
}
// tempFiles.add(tempFile);
try (OutputStream outputStream = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return tempFiles;
}
All file names i want to set to UUID.pdf (example - 3527a982-cead-4a33-9c3f-8ge8492e2add.pdf)
File.createTempFile(...) gives me my UUID with random number suffix (example - 3527a982-cead-4a33-9c3f-8ge8492e2add1234567890.pdf), that is why i rename files with tempFile.renameTo(renamedFile)
In debug mode on breakpoint i can see new correct file name (example - 3527a982-cead-4a33-9c3f-8ge8492e2add.pdf) but when i upload files to S3, they appear there with their names truncated; only the last part after the dash remains from UUID (example - 8ge8492e2add.pdf).
Please help me solve this problem. I want to use temporary files so that the conversion can remain in a separate method and any other programmer using this method does not have to remember that after conversion they need to delete all created Files.
If this cannot be done using Files, tell me a way to send the files but so that the TransferManager does not use the names of the files themselves, and I will somehow specify the names to him in the parameters.