0

我正在使用 MongoDB Stitch 使用 React Native 上传图像,我可以成功上传文本和看似图像的内容,但我无法从 S3 打开图像。

我在 Stitch 函数(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));
  }
};

从客户端我使用react-native-image-picker来选择图像,然后像这样上传:

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)
      })
    }
  }

以及调用 Stitch 函数的客户端函数:

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

我可以成功地将看似图像文件的内容上传到 S3,但是当我下载文件时,我无法打开它:

在此处输入图像描述

4

1 回答 1

1

您必须将 base64 图像转换为 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),
})
于 2019-04-05T17:04:49.900 回答