react-native - 如何使用 Axios 将本地设备图像上传到 S3 存储桶
问题描述
我需要将图像直接上传到 S3 存储桶。我正在使用 react native 和 react-native-image-picker 来选择照片。这将返回一个本地图像 uri。这是我现在的代码。
ImagePicker.showImagePicker(options, response => {
var bodyFormData = new FormData(); // If I don't use FormData I end up
// uploading the json not an image
bodyFormData.append('image', {
uri: response.uri, // uri rather than data to avoid loading into memory
type: 'image/jpeg'
});
const uploadImageRequest = {
method: 'PUT',
url: presignedS3Url,
body: bodyFormData,
headers: {
'Content-Type: 'multipart/form-data'
}
};
axios(uploadImageRequest);
});
这几乎可以工作..当我检查我的 S3 存储桶时,我有一个几乎是图像的文件。它具有以下格式
--Y_kogEdJ16jhDUS9qhn.KjyYACKZGEw0gO-8vPw3BcdOMIrqVtmXsdJOLPl6nKFDJmLpvj^M
content-disposition: form-data; name="image"^M
content-type: image/jpeg^M
^M
<Image data>
如果我手动进入并删除标题,那么我就有了我的形象!但是,我需要将图像直接上传到 S3,客户将抓取并期望已经采用正确的图像格式。
我可以使用 response.data 并解码为字符串并直接上传它来完成这项工作,但为了记忆,我宁愿不这样做。
解决方案
使用带有预签名 URL 的 AJAX 将图像从客户端上传到 S3
自从您发布问题以来已经有一段时间了,所以我想您已经找到了解决方案,但是无论如何...我也在尝试做同样的事情,即使用 axios 将图像上传到 S3,但我就是无法做到好好工作。幸运的是,我发现我们可以很容易地使用普通的 AJAX 来解决这个问题:
const xhr = new XMLHttpRequest();
xhr.open('PUT', presignedS3Url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('Image successfully uploaded to S3');
} else {
console.log('Error while sending the image to S3.\nStatus:', xhr.status, "\nError text: ", xhr.responseText);
}
}
}
xhr.setRequestHeader('Content-Type', 'image/jpeg');
xhr.send({ uri: imageUri, type: 'image/jpeg', name: fileName});
推荐阅读
- python - 如何根据原始列表中与设定值不同的元素对列表进行切片(或创建子列表)
- python - 有人可以解释这个使用递归的代码吗?
- python - 在 python 类中使用固定装置
- arrays - 使用python中的键对JSON对象进行分组
- intellij-idea - 如何在 Linux 上更新 Intellij 2018.2 中的 subversion 版本?
- java - JAVA_HOME 路径问题
- django - 如何在 Django 模型上测试外键对象
- c# - asp.net继承和类混淆
- api - 从多部分/表单数据主体 WSO2 中提取参数
- ruby-on-rails - Rails 2.3.2 - content_type "application/pdf" 问题