我正在使用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,但是当我下载文件时,无法打开它:
答案 0 :(得分: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),
})