1
public void upload(MultipartFile multipartFile, boolean publicAccess) {
    String fileName = this.generateUniqueFilename(multipartFile);

    try {
        File file = new File(Objects.requireNonNull(fileName));
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(multipartFile.getBytes());
        outputStream.close();

        PutObjectRequest request = new PutObjectRequest(this.awsS3UploadBucket, fileName, file);

        if (publicAccess) {
            request.withCannedAcl(CannedAccessControlList.PublicRead);
        }

        this.amazonS3.putObject(request);

    } catch (Exception exception) {
        logger.error("error [" + exception.getMessage() + "] occurred while uploading [" + fileName + "] ");
    }
}

The generateUniqueFilename generates a unique name for the uploaded file. For example 143119066552807424.png.

When the code runs I got this exception

error [The request signature we calculated does not match the signature you provided. Check your key and signing method. 
(Service: Amazon S3; Status Code: 403; Error Code: SignatureDoesNotMatch; Request ID: XXX; S3 Extended Request ID: XXXX)] occurred while uploading [143119066552807424.png] 

I did some research on google but found no resource which explains how I can sign the request right. Can anyone explain why this code isn't running?

Markus
  • 1,909
  • 4
  • 26
  • 54
  • Make sure the fileName is correct when generating a pre-signed URL if you are doing that, but also in your upload. – Derrops Jan 30 '20 at 23:17
  • The fileName look's like `143294821211516928.png`. `file.getName()` returns the same result. Where is the pre-signed URL generated? – Markus Jan 31 '20 at 10:03
  • You first need to generate a pre-signed url with the name of the file, then using that URL, you can upload to S3, with a file whose name is the same, maybe review S3 pre-signed URL, private/public buckets, all that good stuff, I think your missing some of the concepts. – Derrops Jan 31 '20 at 10:31
  • Consider removing the Spring tags, your question has nothing to do with Spring. – Derrops Jan 31 '20 at 10:31
  • Everything works fine if I use this approach https://stackoverflow.com/a/48081970/10115037 – Markus Jan 31 '20 at 10:32
  • the error message suggests, that your aws key(s)/credentials are wrong... – xerx593 Jan 31 '20 at 10:38
  • 1
    @xerx593 Thank you. Uploading a file with the same credentials using the aws cli works fine. So I think the credentials are not the problem. – Markus Jan 31 '20 at 10:39
  • please verify "same credentials" (meticulously) ... i am sure you already checked: https://aws.amazon.com/premiumsupport/knowledge-center/s3-403-upload-bucket/ (?) ..the exact wording of the error message led me also to this: https://docs.aws.amazon.com/general/latest/gr/signature-v4-troubleshooting.html – xerx593 Jan 31 '20 at 11:29

0 Answers0