How to Upload a File or Image to AWS S3 Bucket from React Native App

Upload a File or Image to AWS S3 Bucket

In this post, I’ll show you how to Upload File/Image to AWS S3 bucket from React Native App works for Android and iOS both . This example will cover how to pick any image from the file system and upload it to the AWS S3 bucket. I have not mentioned so many things about AWS s3 setup as it is the part of server side development.

What is AWS and S3 Bucket?

Amazon Web Services is a subsidiary of Amazon providing on-demand cloud computing platforms and APIs to individuals, companies, and governments, on a metered pay-as-you-go basis.

Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. You can use it for many use cases, such as

  1. data lakes
  2. websites
  3. mobile applications
  4. backup and restore
  5. archive
  6. enterprise applications
  7. IoT devices
  8. big data analytics

If you are not clear after reading the S3 definition you can think of a remote hard disk where you can store n number of file which can be arranged in the same folder manner which we use for our local file storage. If you have used windows OS then compare bucket as the C, D or the other drive of your computer.

How to set up an Amazon S3 bucket?

Buckets can be managed using either the console provided by Amazon S3 or programmatically using the AWS SDK. You can follow the following steps to setup Amazon S3 bucket

1. Sign up for an Amazon S3 Account

To use S3 buckets, you will first need an Amazon S3 account. To sign up, go to the S3 Service Page and click the “Get started with Amazon S3” button. you will need a credit card/ debit card for that but don’t worry Amazon Web Services are free for 12 starting months and you can also deactivate your account anytime.

2. Locate your credentials

To locate the credentials for your account, you will need to:

  • Go to the AWS Management Console
  • Hover over your profile name in the top right menu and click “My Security Credentials”
  • Scroll to the “Access Keys” section
  • Click on “Create New Access Key”
  • Take note of both the Access Key ID (YOUR_AMAZON_S3_KEY) and Secret Access Key(YOUR_AMAZON_S3_SECRET)

Important For security reasons, we recommend setting up an IAM user in case of production deployment. In case you want to use IAM user then you need to setup the these policies.

3. Create a bucket

To create an S3 bucket, use the S3 Management Console. We recommend any of the following:

Make sure to take note of the name of your Bucket Name (YOUR_AMAZON_S3_BUCKET) after you create it.

Once you have your Amazon S3 bucket setup with you, you can proceed further.

How to upload any File or Image to AWS S3 Bucket?

To upload the image or file we are going to use react-native-aws3 library. React Native AWS3 is a module for uploading files to S3. Unlike other libraries out there, there are no native dependencies.

It provides a simple RNS3 component which has put function to start uploading.

RNS3.put(file, options).then(response => {
  if (response.status !== 201)
    throw new Error("Failed to upload image to S3");
  console.log(response.body);
  /**
   * {
   *   postResponse: {
   *     bucket: "your-bucket",
   *     etag : "9f620878e06d28774406017480a59fd4",
   *     key: "uploads/image.png",
   *     location: "https://your-bucket.s3.amazonaws.com/***.png"
   *   }
   * }
   */
});

To use RNS3 we have to provide file details

const file = {
  uri: "**Your selected file path**",
  name: "**File name**",
  type: "**File Type**"
}

and options with accessKey and secretKey

const options = {
  keyPrefix: '**Your Key Prefix**', // Ex. myuploads/
  bucket: '**Name of Your AWS Bucket**', // Ex. aboutreact
  region: '**Region**', // Ex. ap-south-1
  accessKey: '**Replace your Access Key**',
  // Ex. AKIH73GS7S7C53M46OQ
  secretKey: '**Replace your Secrete Key**',
  // Ex. Pt/2hdyro977ejd/h2u8n939nh89nfdnf8hd8f8fd
  successActionStatus: 201,
}

Upload to AWS S3 Bucket Example Description

In this example, We are going to create one Screen with two buttons. One button to pick the file from the file system and another button to upload the file on AWS S3 Bucket.

If you face any challenge with the image picker then you can see Example of Image Picker in React Native it will help you to solve your problems. Now let’s get started with the Example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To install the dependency open the terminal and jump into your project

cd ProjectName

Install following dependency to pick the image from gallery

npm install react-native-image-picker --save

To upload file on AWS S3 we need to install following dependency

npm install --save react-native-aws3

CocoaPods Installation

Now we need to install pods

cd ios && pod install && cd ..

IOS Permission to Read the Storage

1. Open the project YourProject -> ios -> YourProject.xcworkspace in XCode. Click on Project (ImagePickerExample in my case) from the left sidebar and you will see multiple options in the workspace.

2. Select info tab which is info.plist

3. Click on the plus button to add following permission key and value which will be visible when permission dialog pops up.

  • If you are allowing user to select image/video from photos, add “Privacy – Photo Library Additions Usage Description”.

 

KeyValue
Privacy – Photo Library Additions Usage DescriptionApp needs photo library Access

Code for the File Upload to AWS S3 Bucket in React Native

Open App.js in any code editor and replace the code with the following code. Please remember to update following things before running the code

{
  keyPrefix: '**Your Key Prefix**', // Ex. myuploads/
  bucket: '**Name of Your AWS Bucket**', // Ex. aboutreact
  region: '**Region**', // Ex. ap-south-1
  accessKey: '**Replace your Access Key**',
  // Ex. AKIH73GS7S7C53M46OQ
  secretKey: '**Replace your Secrete Key**',
  // Ex. Pt/2hdyro977ejd/h2u8n939nh89nfdnf8hd8f8fd
  successActionStatus: 201,
}

App.js

// How to Upload any File or Image to AWS S3 Bucket from React Native App
// https://aboutreact.com/react-native-upload-file-to-aws-s3-bucket/

// Import React
import React, {useState} from 'react';
// Import required components
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Image,
} from 'react-native';
import {RNS3} from 'react-native-aws3';

import {launchImageLibrary} from 'react-native-image-picker';

const App = () => {
  const [filePath, setFilePath] = useState({});
  const [uploadSuccessMessage, setUploadSuccessMessage] = useState('');

  const chooseFile = () => {
    let options = {
      mediaType: 'photo',
    };
    launchImageLibrary(options, (response) => {
      console.log('Response = ', response);
      setUploadSuccessMessage('');
      if (response.didCancel) {
        alert('User cancelled camera picker');
        return;
      } else if (response.errorCode == 'camera_unavailable') {
        alert('Camera not available on device');
        return;
      } else if (response.errorCode == 'permission') {
        alert('Permission not satisfied');
        return;
      } else if (response.errorCode == 'others') {
        alert(response.errorMessage);
        return;
      }
      setFilePath(response);
    });
  };

  const uploadFile = () => {
    if (Object.keys(filePath).length == 0) {
      alert('Please select image first');
      return;
    }
    RNS3.put(
      {
        // `uri` can also be a file system path (i.e. file://)
        uri: filePath.uri,
        name: filePath.fileName,
        type: filePath.type,
      },
      {
        keyPrefix: '**Your Key Prefix**', // Ex. myuploads/
        bucket: '**Name of Your AWS Bucket**', // Ex. aboutreact
        region: '**Region**', // Ex. ap-south-1
        accessKey: '**Replace your Access Key**',
        // Ex. AKIH73GS7S7C53M46OQ
        secretKey: '**Replace your Secrete Key**',
        // Ex. Pt/2hdyro977ejd/h2u8n939nh89nfdnf8hd8f8fd
        successActionStatus: 201,
      },
    )
      .progress((progress) =>
        setUploadSuccessMessage(
          `Uploading: ${progress.loaded / progress.total} (${
            progress.percent
          }%)`,
        ),
      )
      .then((response) => {
        if (response.status !== 201)
          alert('Failed to upload image to S3');
        console.log(response.body);
        setFilePath('');
        let {
          bucket,
          etag,
          key,
          location
        } = response.body.postResponse;
        setUploadSuccessMessage(
          `Uploaded Successfully: 
          \n1. bucket => ${bucket}
          \n2. etag => ${etag}
          \n3. key => ${key}
          \n4. location => ${location}`,
        );
        /**
         * {
         *   postResponse: {
         *     bucket: "your-bucket",
         *     etag : "9f620878e06d28774406017480a59fd4",
         *     key: "uploads/image.png",
         *     location: "https://bucket.s3.amazonaws.com/**.png"
         *   }
         * }
         */
      });
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        How to Upload any File or Image to AWS S3 Bucket{'\n'}
        from React Native App
      </Text>
      <View style={styles.container}>
        {filePath.uri ? (
          <>
            <Image
              source={{uri: filePath.uri}}
              style={styles.imageStyle}
            />
            <Text style={styles.textStyle}>
              {filePath.uri}
            </Text>
            <TouchableOpacity
              activeOpacity={0.5}
              style={styles.buttonStyleGreen}
              onPress={uploadFile}>
              <Text style={styles.textStyleWhite}>
                Upload Image
              </Text>
            </TouchableOpacity>
          </>
        ) : null}
        {uploadSuccessMessage ? (
          <Text style={styles.textStyleGreen}>
            {uploadSuccessMessage}
          </Text>
        ) : null}
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={chooseFile}>
          <Text style={styles.textStyleWhite}>
            Choose Image
          </Text>
        </TouchableOpacity>
      </View>
      <Text style={{textAlign: 'center'}}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    backgroundColor: '#fff',
  },
  titleText: {
    fontSize: 22,
    fontWeight: 'bold',
    textAlign: 'center',
    paddingVertical: 20,
  },
  textStyle: {
    padding: 10,
    color: 'black',
    textAlign: 'center',
  },
  textStyleGreen: {
    padding: 10,
    color: 'green',
  },
  textStyleWhite: {
    padding: 10,
    color: 'white',
  },
  buttonStyle: {
    alignItems: 'center',
    backgroundColor: 'orange',
    marginVertical: 10,
    width: '100%',
  },
  buttonStyleGreen: {
    alignItems: 'center',
    backgroundColor: 'green',
    marginVertical: 10,
    width: '100%',
  },
  imageStyle: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
    margin: 5,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

react_native_aws_s3_upload1   react_native_aws_s3_upload2   react_native_aws_s3_upload3   react_native_aws_s3_upload4 react_native_aws_s3_upload5 react_native_aws_s3_upload6

This is How to Upload a File or Image to AWS S3 Bucket from React Native App. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.