简体   繁体   中英

AWS S3 Image Upload Error: Unsupported Body Payload Object

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM