我正在尝试使用我的Spring Boot应用程序将图像和PDF上传到AWS S3。它们以损坏的格式上传,没有任何错误。文本文件可以成功上传。
public String uploadDocumentToS3(String bucketName, MultipartFile file) {
Map<String, String> mimeTypes = new HashMap<String, String>();
mimeTypes.put("jpeg", "image/jpeg");
mimeTypes.put("jpg", "image/jpeg");
mimeTypes.put("png", "image/png");
mimeTypes.put("pdf", "application/pdf");
mimeTypes.put("txt", "text/plain");
String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
LOGGER.info("File Extension " + fileExtension + " MIME " + mimeTypes.get(fileExtension));
final String s3FileName = LocalDateTime.now() + "_" + file.getOriginalFilename();
LOGGER.info("Uploading file on S3 with name= " + s3FileName);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(mimeTypes.get(fileExtension));
metadata.setContentLength(file.getSize());
metadata.addUserMetadata("title", "Business Onboarding Doc");
PutObjectRequest request;
try {
request = new PutObjectRequest(bucketName, s3FileName, file.getInputStream(), metadata);
amazonS3.putObject(request);
} catch (Exception e) {
LOGGER.error("Error while uploading S3 file using InputStream " + e.getLocalizedMessage());
}
return s3FileName;
}
以下是我们使用的依赖关系。
compile group: 'com.amazonaws', name: 'aws-java-sdk', version: '1.11.946'