Search code examples
mongodbreact-nativeamazon-s3mongodb-stitch

Images uploaded to S3 using MongoDB Stitch cannot be opened


I'm using MongoDB Stitch to upload images using React Native, and I can successfully upload text and what appears to be an image, but I can't open the image from S3.

I'm using the following code from their example in a Stitch function (https://docs.mongodb.com/stitch/services/aws/):

exports = async function(key, body) {
  const s3 = context.services.get('MY_S3_SERVICE').s3("us-east-1");
  try {
    const result = await s3.PutObject({
      "Bucket": "my_bucket_on_s3",
      "Key": key,
      "Body": body
    });
    console.log(EJSON.stringify(result));
    return result;
  } catch(error) {
    console.error(EJSON.stringify(error));
  }
};

From the client side I'm using react-native-image-picker to pick the image, and upload it like so:

handleSelectedImage = response => {
    if (response.didCancel) {
      console.log('User cancelled image picker')
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error)
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton)
    } else {
      const source = { uri: response.uri }
      //const s = { uri: 'data:image/jpeg;base64,' + response.data }

      const imageId = generateUniqueId()
      const fileType = '.jpg'
      const key = imageId + fileType

      uploadImage(key, source.uri).then(result => {
        console.log('Did upload image!', result)
      })
    }
  }

And the client side function that calls the Stitch function:

export const uploadImage = (key, body) => {
  const client = Stitch.defaultAppClient
  return client.callFunction('uploadImage', [key, body])
}

I can successfully upload what appears to be an image file to S3, but when i download the file, I can't open it:

enter image description here


Solution

  • You have to convert the base64 image to BSON.Binary:

    context.services.get("MY_S3_SERVICE").s3("us-east-1").PutObject({
        Bucket: "my_bucket_on_s3",
        Key: "hello.jpg",
        ContentType: "image/jpeg",
        Body: BSON.Binary.fromBase64("iVBORw0KGgoAA... (rest of the base64 string)", 0),
    })