【发布时间】:2016-08-24 14:04:39
【问题描述】:
我正在开发一个 React Native 应用程序,我试图从用户的相机胶卷中获取图像,将它们转换为 base64 字符串并将它们存储到 Amazon S3 以供以后使用。
在这篇博文之后,我可以获取用户的相机胶卷并将图像转换为 base64: react-native-creating-a-custom-module-to-upload-camera-roll-images
然后,我将 base64 字符串图像数据发送到一个简单的 Express 服务器,该服务器已设置为将数据发布到我的 Amazon S3 存储桶。
// Only getting first img in camera roll for testing purposes
CameraRoll.getPhotos({first: 1}).then((data) => {
for (let i = 0; i < data.edges.length; i++) {
NativeModules.ReadImageData.readImage(data.edges[i].node.image.uri, (imageBase64) => {
// Does the string have to be encoded?
// const encodeBase64data = encodeURIComponent(imageBase64);
const obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'img': imageBase64
})
}
fetch('http://localhost:3000/saveImg', obj)
.then((res) => {
console.log(JSON.parse(res._bodyInit));
})
})
}
在这种情况下,我的 imageBase64 变量是一个相当大的字符串,如下所示:/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAA...abX+Yub/API3zf8A7G2Z/wDqdiD/AExyf/kT5R/2Kst/9QqB0x6H6GuBbr1R6D2foz+ZT/gof/yep8bf934f/wDqC6PX96+Cn/JruFf+6z/6t8UfwP4wf8nM4n9Mq/8AVbRPjOv1I/OAoA//2Q==
... 还有几个字符。
我正在将此 base64 字符串发送到我的快递服务器并发布数据:
app.post('/saveImg', function(req, res) {
// this will be moved once testing is complete
var s3Bucket = new AWS.S3( { params: {Bucket: '[my_bucket_name]'} } );
// Do I need to append this string to the image?
var baseImg = 'data:image/png;base64,' + req.body.img;
var data = {
Key: test_img,
Body: req.body.img,
ContentEncoding: 'base64',
ContentType: 'image/png'
};
s3Bucket.putObject(data, function(err, data){
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
res.send(data);
console.log('successfully uploaded the image!');
}
});
// res.send(base64data)
});
我成功地将数据发送到 Amazon S3 并在存储桶中查看了我的图像文件,但是当我尝试访问链接以查看实际图像本身或将其拉入我的 React Native 应用程序时,我什么也得不到。
ie 如果我在 Amazon S3 中访问上面的 test_img 的 URL,我会得到:
https://s3.amazonaws.com/my_bucket_name/test_img
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>BCE6E07705CF61B0</RequestId>
<HostId>
aF2l+ucPPHRog1QaaXjEahZePF0A9ixKR0OTzlogWFHYXHUMUeOf2uP7D/wtn7hu3bLWG8ulKO0=
</HostId>
</Error>
我已经手动将图像上传到同一个存储桶,它们的链接看起来很好,而且我还可以将它们拉到我的 React Native 应用程序中查看。
我的问题是在获取 base64 字符串数据并将其发送到我的 Express 服务器以保存到我的存储桶之间我做错了什么? 是否必须对 base64 字符串进行编码? 在将 base64 字符串发送到 Express 之前,是否需要将其转换为 Blob?
感谢您的帮助!
【问题讨论】:
-
订阅,我也需要这个
标签: amazon-s3 base64 react-native