Search code examples
react-nativeamazon-s3aws-sdkcreate-react-native-appaws-amplify

create react native app AWS S3 getObject use file


my RN app is created with create react native app. Now i want to display some images of my aws s3 bucket.

So this works fine, if i make the images public and display them with:

<Image source={props.pic_url} />

But of course the images should be private, so i try to load them with the S3 API:

export const s3 = new AWS.S3({
  apiVersion: '2006-03-01',
  params: {Bucket: BUCKET_NAME}
});
let get_pic_params = {
  Bucket: BUCKET_NAME,
  Key: "pics/0001.jpg"
}
s3.getObject(get_pic_params, function(err, data) {
    if (err) {
      console.log('There was an error getting a pic: ' + err.message);
    } else {
      console.log(data);
    }
  });

Output:

Object {
  "AcceptRanges": "bytes",
  "Body": Object {
    "data": Array [
      71,
      73,
      70,
      56,
      .
      .
      .
      59,
    ],
    "type": "Buffer",
  },
  "ContentLength": 45212,
  "ContentType": "image/jpeg",
  "ETag": "\"c90bf3bb902711c8b1386937341ca9ec\"",
  "LastModified": 2017-09-13T12:40:35.000Z,
  "Metadata": Object {},
}

This works fine, but i dont want to get the data as a console.log i want to display them as an Image. How can i do that with create-react-native-app?

I tried react-native-fs but that does not work with create-react-native-app


Solution

  • I did not test this but I did compile couple of information that can work for you. Please try it and see if its gonna work for you.

    First of all you are receiving an array buffer from S3. You can possibly convert this arrayBuffer to buffer and then convert this buffer to a Base64 string that can be used as a source for Image component.

    I think you can use this buffer library for this.

    const buffer = Buffer.from(arrayBuffer); //returned data 
    const base64ImageData = buffer.toString('base64');
    const imgSrc = "data:image/png;base64," + base64ImageData;
    <Image source={{uri: imgSrc, scale: 1}} style={{ height: 80, width: 80}}/>