Search code examples
amazon-web-servicesreact-nativeamazon-s3expoaws-amplify

React-native upload image to aws S3 via Expo ImagePicker


I want to upload a Photo to the S3 bucket, I current using the Expo and aws-amplify to approach this.

the code to fetch the local image is below:

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)));

After I get the image I upload the image to s3 bucket via { Storage } from 'aws-amplify'

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));

After I uploaded the image, I tried to open the image in the S3 bucket. The image can not be opened properly, also I can not access the image publicly unless I mark the file public in the S3 bucket.


Solution

  • Just figure out what the problem is. The put() method from Storage requires a blob for the argument. Here is what I did to achieve this.

    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));
        });
    });