Uploading Images to S3 Using Aws Sdk From React Native

Mega Packet Auction is ON! Get ALL of our React Native codebases at eighty% OFF discount 🔥

In this tutorial we will build a React Native app that allows users to upload images and videos from their photographic camera and photo library straight into a AWS S3 saucepan. As AWS is the leader of deject providers, a huge part of the React Native ecosystem is using AWS as the backend for their app. With the release of AWS Dilate, using AWS as backend for a React Native app has never been easier to implement.

The app we are going to build in this React Native AWS tutorial will upload and store image and video files using Amazon S3 bucket. In this article, nosotros volition teach you how epitome and video storage works in React Native using AWS S3 bucket. Every single step of the implementation will be detailed and no stones will be left unturned. So let us get into it.

react-native-aws-s3-bucket

For those who are not familiar with AWS S3 buckets already, here'southward is the formal definition of Amazon S3 and what a bucket is:

Amazon S3 stores information as objects inside buckets . An object consists of a file and optionally whatever metadata that describes that file. To store an object in Amazon S3, you upload the file you want to store to a saucepan. When you upload a file, y'all tin can ready permissions on the object and any metadata.

one. Creating the React Native Project

Open a new Terminal example, and run the following

react-native init s3bucket_storage_example

Then we install and configure the required dependencies, using yarn:

yarn add react-native-image-picker react-native-video @react-native-community/netinfo @react-native-async-storage/async-storage

or using npm:

npm install react-native-image-picker react-native-video @react-native-community/netinfo @react-native-async-storage/async-storage -S

For iOS you too need to install the pods past running

cd ios && pod install

So add the post-obit snippet to your ios/<projectName>/Info.plist to request Photo Library permissions.

<central>NSPhotoLibraryUsageDescription</key> <string>$(PRODUCT_NAME) would like access to your photo gallery.</string>
2. Picking Photos & Videos from Photo Library

Our start chore here is to fetch an prototype or video from the user's photo library. In order to accomplish that, nosotros are going to leveragereact-native-epitome-picker to choice media files from the library. To exist able to brandish and play videos, we are also going to use the npm packagereact-native-video. Now, let's replace all yourApp.js file with the following source code:

import React, {useState} from 'react'; import {   View,   Text,   TouchableOpacity,   StyleSheet,   Alert,   Image, } from 'react-native'; import {launchImageLibrary} from 'react-native-image-picker'; import Video from 'react-native-video';  part S3StorageUpload() {   const [nugget, setAsset] = useState(null);    const selectFile = async () => {     wait launchImageLibrary({mediaType: 'mixed'}, result => {       if (!result.assets) {         Alert.alert(result.errorMessage);         return;       }       setAsset(issue.assets[0]);     });   };    render (     <View style={styles.container}>       <TouchableOpacity onPress={selectFile}>         <Text style={styles.button}>SELECT {asset ? 'ANOTHER' : ''} FILE</Text>       </TouchableOpacity>       {asset ? (         asset.type.dissever('/')[0] === 'image' ? (           <Image             style={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         ) : (           <Video             style={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         )       ) : nothing}       {nugget && (         <>           <TouchableOpacity onPress={() => setAsset(null)}>             <Text style={styles.cancelButton}>Remove Selected Paradigm</Text>           </TouchableOpacity>         </>       )}     </View>   ); }  const styles = StyleSheet.create({   button: {     fontSize: 20,     color: '#fff',     backgroundColor: 'blueish',     paddingVertical: xx,     paddingHorizontal: xxx,     marginHorizontal: 20,     marginVertical: 10,     textAlign: 'centre',     fontWeight: 'bold',   },   cancelButton: {     backgroundColor: '#fff',     color: 'blue',   },   selectedImage: {     width: 175,     height: 200,     marginTop: 20,   },   container: {     flex: i,     justifyContent: 'center',     alignItems: 'center',   }, });  consign default S3StorageUpload;        

At present, run your mobile app in your device, simulator or emulator. You volition notice that you at present are able to pick a photograph or a video from your photo library.

three. AWS Amplify Setup

Now that our mobile application UI is pretty much implemented, let's focus on how to set up the actual backend storage, and how we tin integrate the mobile React Native app to communicate with the AWS backend, securely and finer.

a. Create A New AWS Amplify Project

Caput over to the AWS website and create a new AWS Amplify project.

react native s3 bucket

b. Install the AWS Amplify CLI

Next, we need to install AWS Amplify CLI on our local machine by running the following command on your terminal.

npm install -thousand @aws-amplify/cli

This AWS Amplify CLI volition enable us run AWS commands anywhere on our local machine. For example, we can update our local AWS configuration by pulling our AWS backend and updating our backend past pushing local configuration changes to the backend.

c. Pull The AWS Dilate Project into the React Native Codebase

Pull your already created Amplify backend project into your React Native project by running the following command at the root of your React Native project:

amplify pull --appId <appID> --envName <appName>

Note: Please be sure to verify the app login on your Amplify UI Admin, so select your preferred editor, type of app equally Javascript, and framework equally React Native. You need to enter Y when asked if you wish to alter the backend. Default entries should be allowed for the remaining prompts.

c. Enable Storage in the AWS Amplify Project

At the root of your React Native project run amplify add storage to add storage to your backend project as seen in the beneath screenshot. After that is done you should button your new project configurations to the backend past running dilate push.

Note: On prompted yous should select Content (Images, audio, video, etc.). Calculation authentication or functions to your project is non mandatory and every other options tin can be left every bit their default value.

3. Upload Photos & Videos to AWS S3 Bucket in React Native

We've finally reached the core part of this tutorial. So far, we set the React Native project, the AWS backend project, and we congenital the integration between these two. We've also implemented the ability for the users to pick photos from the gallery, so all nosotros need to do now is go those photos and send them over to the S3 cloud.

a. Install aws-amplify Into the React Native Project

yarn add together aws-amplify

or

npm install aws-amplify -S

b. And so Import AWS Amplify into Your App.js

import Amplify, {Storage} from 'aws-amplify';

and configure your AWS Amplify:

import awsconfig from './src/aws-exports'; Amplify.configure(awsconfig);

c. Add together the following two states to the S3StorageUpload

const [progressText, setProgressText] = useState(''); const [isLoading, setisLoading] = useState(imitation);

progressText will be used to display the progress of the upload and isLoading to aid disable our buttons from performing any action while the image is getting uploaded.

d. Add the following handler and helper functions

First nosotros accept to convert our URI to a blobusing fetchResourceFromURI then uploadResource uploads the file using the asset URI every bit the cardinal.A success callback is passed to recollect the key of the uploaded file and this key is important considering you need information technology to get the URI of the resource URI from the backend.

const fetchResourceFromURI = async uri => {   const response = await fetch(uri);   panel.log(response);   const blob = await response.blob();   return hulk; };  const uploadResource = async () => {   if (isLoading) return;   setisLoading(true);   const img = await fetchResourceFromURI(asset.uri);   return Storage.put(asset.uri, img, {     level: 'public',     contentType: asset.type,     progressCallback(uploadProgress) {       setProgressText(         `Progress: ${Math.circular(           (uploadProgress.loaded / uploadProgress.total) * 100,         )} %`,       );       console.log(         `Progress: ${uploadProgress.loaded}/${uploadProgress.total}`,       );     },   })     .then(res => {       setProgressText('Upload Washed: 100%');       setAsset(null);       setisLoading(false);       Storage.become(res.key)         .so(issue => console.log(upshot))         .catch(err => {           setProgressText('Upload Error');           console.log(err);         });     })     .take hold of(err => {       setisLoading(false);       setProgressText('Upload Error');       console.log(err);     }); };

4. Trigger the File Upload to AWS S3 in React Native

return (     <View style={styles.container}>       <TouchableOpacity onPress={selectFile}>         <Text mode={styles.button}>SELECT {asset ? 'Another' : ''} FILE</Text>       </TouchableOpacity>       {asset ? (         asset.blazon.divide('/')[0] === 'prototype' ? (           <Image             way={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         ) : (           <Video             way={styles.selectedImage}             source={{uri: nugget?.uri ?? ''}}           />         )       ) : null}       {asset && (         <>           <TouchableOpacity onPress={uploadResource}>             <Text style={styles.button}>UPLOAD</Text>           </TouchableOpacity>           <TouchableOpacity onPress={() => setAsset(null)}>             <Text mode={styles.cancelButton}>Remove Selected Image</Text>           </TouchableOpacity>         </>       )}       <Text>{progressText}</Text>     </View>   );

In the above snippet we edit and update the UI by adding a button to trigger the uploadResource part. Here's a snippet short clip showing how this works.

5. Deleting a File from AWS S3 Bucket in React Native

Deleting a file is straightforward and can be done by a single part call that takes the file keyequally a required parameters and an optional parameter protectedLevel that specifies the File Admission Level of the file when it was uploaded

await Storage.remove('img.png');

six. File Access Levels in AWS

There are 3 File Access Levels namely: public, protected, private. The default level is public for case when uploading a file using Storage.get('video.mp4') unless configured otherwise as follows:

Storage.configure({ level: 'private' });

According to the official documentation:

  • Public: Accessible past all users of your app. Files are stored under thepublic/ path in your S3 saucepan.

  • Protected: Readable by all users, but writable but by the creating user. Files are stored netherprotected/{user_identity_id}/ where theuser_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.

  • Private: Merely attainable for the individual user. Files are stored underprivate/{user_identity_id}/ where theuser_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.

Note

Y'all may get the post-obit fault when yous run your app:Error: jest-haste-map: Haste module naming collison:

To fix this outcome, simply delete thedilate/#electric current-cloud-backend folder and re-build the app.

Conclusion

In this tutorial, we take successfully been able to set an AWS Dilate storage project in your AWS Dilate account, then nosotros configured it on your local machine and integrated it with the React Native project. Implementation wise, we built a feature that allows the users to pick photos and videos from their photo gallery and upload it to the S3 bucket deject. We've also learned how to remove those files from the cloud, and also, we got familiar with the various privacy levels for the AWS file cloud.

If you lot want to skip the tutorial, and spring straight into the code, you can find the Github React Native AWS S3 Saucepan projection here. If you institute this helpful, please give us a star on Github and share this commodity with your community / your audience.

ramseyhaost1986.blogspot.com

Source: https://instamobile.io/react-native-tutorials/react-native-aws-s3/

0 Response to "Uploading Images to S3 Using Aws Sdk From React Native"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel