0

I try to upload a local image to an s3 bucket and keep getting Error: Unsupported body payload object

The image can be jpg, jpeg, or png. I've read that images can only be uploaded to s3 as base64 so I read the file as a base64 string using readAsDataURL, and then create a Buffer with it.

const reader = new FileReader()
reader.readAsDataURL(file)
const base64str = reader.result.replace(/^data:image\/\w+;base64,/, "");
const fileContent = Buffer.from(base64str,'base64')

The above code is executed on the react frontend where fileContent is set to a variable through a hook, and that variable gets PUT-ed to my server with

static uploadImage = (id, fileContent) => {
  return axios.put(ROOT_URL + "/images/" + id, fileContent);
}

Then its uploaded with

await s3.upload({
  Bucket: BUCKET_NAME,
  Key: KEY,
  Body: fileContent,
  ContentType: TYPE,
}).promise();

I have tried many different solutions I've found on this website, and still receive the error. Not sure what I am missing.

EDIT: Here is one of the threads that I found helpful, but did not fix the error. Uploading base64 encoded Image to Amazon S3 via Node.js

1 Answers1

0

Not sure where you read that images must be base64, but you can simply read the file content with something like fs and upload it to S3 as it is.

// Read content from the file
const fileContent = fs.readFileSync(fileName);

// Setting up S3 upload parameters
const params = {
  Bucket: BUCKET_NAME,
  Key: 'cat.jpg', // File name you want to save as in S3
  Body: fileContent
};

// Uploading files to the bucket
await s3.upload(params).promise();
Andre.IDK
  • 1,951
  • 13
  • 17
  • I don't think this is possible, I read the file in react on the front end so I cannot use `fs` – Spartan26783 Dec 01 '20 at 09:29
  • @Spartan26783 your question says that the file is put on the server via a PUT request, and then on S3. I assumed that happens after is already on the server. – Andre.IDK Dec 01 '20 at 09:31
  • "The above code is executed on the react frontend where `fileContent` is set to a variable through a hook, and that variable gets PUT-ed to my server" So I am setting the file to a variable using react hook, and then using a put request to send that to the server. – Spartan26783 Dec 01 '20 at 09:34
  • Any updates? I've attempted some more solutions now. Any idea why AWS may not be accepting base64 strings? Also still looking for an `fs` workaround, the only that I can think of is `FileReader` – Spartan26783 Dec 02 '20 at 02:56