首页 > 解决方案 > 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-web-servicesamazon-s3file-uploadaws-java-sdk

解决方案


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


推荐阅读