amazon-web-services - AmazonClientException:更多数据读取的长度与预期不同
问题描述
当我尝试将内容上传到 Amazon S3 存储桶时,我收到 AmazonClientException:读取的数据长度与预期不同。
这是我的代码。
public Object uploadFile(MultipartFile file) {
String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
log.info("uploadFile-> starting file upload " + fileName);
Path path = Paths.get(file.getOriginalFilename());
File fileObj = new File(file.getOriginalFilename());
try (FileOutputStream os = new FileOutputStream(fileObj)) {
os.write(file.getBytes());
os.close();
String uploadFilePath = bucketName + "/" + uploadPath;
s3Client.putObject(new PutObjectRequest(uploadFilePath, fileName, fileObj));
Files.delete(path);
} catch (IOException ex) {
log.error("error [" + ex.getMessage() + "] occurred while uploading [" + fileName + "] ");
}
log.info("uploadFile-> file uploaded process completed at: " + LocalDateTime.now() + " for - " + fileName);
return "File uploaded : " + fileName;
}
解决方案
Amazon 建议使用 Amazon S3 Java V2 API 而不是使用 V1。
AWS SDK for Java 2.x 是对 1.x 版代码库的重大重写。它建立在 Java 8+ 之上,并添加了几个经常请求的特性。其中包括对非阻塞 I/O 的支持以及在运行时插入不同 HTTP 实现的能力。
要将内容上传到 Amazon S3 存储桶,请使用此 V2 代码。
public static String putS3Object(S3Client s3,
String bucketName,
String objectKey,
String objectPath) {
try {
Map<String, String> metadata = new HashMap<>();
metadata.put("myVal", "test");
PutObjectRequest putOb = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.metadata(metadata)
.build();
PutObjectResponse response = s3.putObject(putOb,
RequestBody.fromBytes(getObjectFile(objectPath)));
return response.eTag();
} catch (S3Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}
如果您对 V2 不熟悉,请参阅此文档主题:
https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
推荐阅读
- python - 尝试生成 oauth2 令牌时出现 Python 语法错误
- ios - Swift解码字符串JSON失败
- docker - 如何从 Windows 10 操作系统为 ARM32 架构构建 docker 容器映像?
- azure - 用于逻辑应用的 Azure API 管理反向代理
- java - 尝试构建android项目时出现编译器错误
- types - OCaml 函数式语言上的表达式错误
- javascript - 如何在不使用的情况下更改 Material-UI TextField 底部颜色
- flutter - 如何在点击来自 Firebase Flutter 的推送通知时打开特定活动
- data-structures - 如何判断树中的子节点是左子节点还是右子节点
- python - 具有多重继承(mixin)和混合默认选项的 Python @dataclass