Skip to content
Advertisement

Image and PDF files getting corrupted while uploading on AWS S3

I am trying to upload images and PDF on AWS S3 using my Spring Boot app. They are getting uploaded in corrupt format without any error. Text files are uploaded successfully.

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;
}

Below is the dependencies we have used.

compile group: 'com.amazonaws', name: 'aws-java-sdk', version: '1.11.946'

Advertisement

Answer

My code works fine. The issue was in the AWS API Gateway. We need to add '*/*' in the Binary Media Types to make file uploading work.

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

Advertisement