首页 > 解决方案 > 如何使用 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 并解码为字符串并直接上传它来完成这项工作,但为了记忆,我宁愿不这样做。

标签: react-nativeaxiosimage-uploadingreact-native-image-picker

解决方案


使用带有预签名 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});

此代码取自此博客的这篇非常有用的文章


推荐阅读