React-native 通过 Expo ImagePicker 将图片上传到 aws S3

React-native upload image to aws S3 via Expo ImagePicker

我想将照片上传到 S3 存储桶,我目前使用 Expo 和 aws-amplify 来处理这个问题。

获取本地图片的代码如下:

import { ImagePicker } from 'expo';

ImagePicker.launchImageLibraryAsync({
  mediaTypes: 'Images',
  allowsEditing: true,
  aspect: [1, 1],
  base64: true
})
.then(image => dispatch(pickImageSuccess(image)))
.catch(err => dispatch(piclImageFail(err)));

获取图像后,我通过 { Storage } from 'aws-amplify'

将图像上传到 s3 存储桶
import { Storage } from 'aws-amplify';

const file = image.base64;
const imageName = image.uri.replace(/^.*[\\/]/, '');
console.log(imageName);
const access = { level: "public", contentType: 'image/jepg' };
Storage.put(`${username}/${imageName}`, file, access)
  .then(succ => console.log(succ))
  .catch(err => console.log(err));

之后 我上传了图片,我尝试打开 S3 存储桶中的图片。图像无法正常打开,我也无法访问图像 publicly 除非我在 S3 存储桶中标记文件 public。

弄清楚问题出在哪里。 Storage 中的 put() 方法需要一个 blob 作为参数。这是我为实现这一目标所做的工作。

import { ImagePicker } from 'expo';
import mime from 'mime-types';
import { Storage } from 'aws-amplify';


const imageName = image.uri.replace(/^.*[\\/]/, '');
const fileType = mime.lookup(image.uri);
const access = { level: "public", contentType: fileType, };
fetch(image.uri).then(response => {
  response.blob()
    .then(blob => {
      Storage.put(`${username}/${imageName}`, blob, access)
        .then(succ => console.log(succ))
        .catch(err => console.log(err));
    });
});