skip to Main Content

I need to upload an image to S3 using signed URL. I have the image in a base64 string. The below code runs without throwing any error, but at the end I see a text file with base64 content in the S3, not the binary image.

Can you please point out what I am missing?

Generate Signed URL (Lambda function JavaScript)

  const signedUrlExpireSeconds = 60 * 100;
  var url = s3.getSignedUrl("putObject", {
    Bucket: process.env.ScreenshotBucket,
    Key: s3Key,
    ContentType: "image/jpeg",
    ContentEncoding: "base64",
    Expires: signedUrlExpireSeconds,
  });

Upload to S3 (Java Code)

HttpRequest request = HttpRequest.newBuilder().PUT(HttpRequest.BodyPublishers.ofString(body))
        .header("Content-Encoding", "base64").header("Content-Type", "image/jpeg").uri(URI.create(url)).build();

HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

if (response.statusCode() != 200) {
    throw new Exception(response.body());
}

2

Answers


  1. Chosen as BEST ANSWER

    Fixed it while just playing around with the combinations.

    HttpRequest request = HttpRequest.newBuilder().PUT(HttpRequest.BodyPublishers.ofString(body))
    

    Changed to

    HttpRequest request = HttpRequest.newBuilder().PUT(HttpRequest.BodyPublishers.ofByteArray(body))
    

  2. I am not familiar with the AWS JavaScript SDK. But it seems that setting the 'Content-Type' metadata of the object (not the Content-Type of the putObject HTTP request) to 'image/jpeg' should do the trick.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search