上传到aws s3时图像和pdf文件损坏

zsbz8rwp  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(738)

我试图上传图片和pdf的AWSS3使用我的 Spring 启动应用程序。他们被上传到损坏的格式没有任何错误。已成功上载文本文件。

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'
iq3niunx

iq3niunx1#

我的代码运行良好。问题出在awsapi网关上。我们需要补充 '*/*' 在二进制媒体类型,使文件上传工作。
供参考:https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html

相关问题