在 AWS S3 上上传时图像和 PDF 文件被损坏

Har*_*ara 3 java spring amazon-s3 amazon-web-services spring-boot

我正在尝试使用 Spring Boot 应用程序在 AWS S3 上上传图像和 PDF。它们以损坏的格式上传,没有任何错误。文本文件已成功上传。

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;
}
Run Code Online (Sandbox Code Playgroud)

以下是我们使用的依赖项。

compile group: 'com.amazonaws', name: 'aws-java-sdk', version: '1.11.946'
Run Code Online (Sandbox Code Playgroud)

Har*_*ara 5

我的代码工作正常。问题出在 AWS API Gateway 中。我们需要添加'*/*'二进制媒体类型才能使文件上传工作。

供参考: https: //docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html