create react native app AWS S3 getObject use file

4.3k views Asked by At

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

2

There are 2 answers

0
bennygenel On BEST ANSWER

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}}/>
2
Richard On

There are some components for easier uploading/downloading/rendering images from S3 in the Storage Module of the AWS Amplify library: https://github.com/aws/aws-amplify/blob/master/media/storage_guide.md

React Native extensions for AWS Amplify are available via npm:

npm install -g @aws-amplify/cli

From there you will need to configure your project. The up to date instructions are available here: https://aws-amplify.github.io/media/get_started.

For your use case you might use S3Album:

import { S3Album } from 'aws-amplify-react';

render() {
    const path = // path of the list;
    return <S3Album path={path} />