Uploading Videos to S3 From React Native

Mega Bundle Sale is ON! Go 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 camera and photo library directly into a AWS S3 bucket. As AWS is the leader of cloud providers, a huge part of the React Native ecosystem is using AWS as the backend for their app. With the release of AWS Amplify, 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 saucepan. In this article, we volition teach yous how image and video storage works in React Native using AWS S3 saucepan. Every unmarried pace of the implementation volition exist detailed and no stones will be left unturned. Then let u.s.a. get into it.

react-native-aws-s3-bucket

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

Amazon S3 stores data as objects within buckets . An object consists of a file and optionally any metadata that describes that file. To shop an object in Amazon S3, you upload the file you want to store to a bucket. When y'all upload a file, y'all tin gear up permissions on the object and any metadata.

ane. Creating the React Native Projection

Open a new Final case, 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 also need to install the pods by running

cd ios && pod install

And then add the following snippet to your ios/<projectName>/Info.plist to request Photograph Library permissions.

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

Our outset task hither is to fetch an image or video from the user's photo library. In order to achieve that, nosotros are going to leveragereact-native-image-picker to pick media files from the library. To exist able to display 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-epitome-picker'; import Video from 'react-native-video';  office S3StorageUpload() {   const [asset, setAsset] = useState(null);    const selectFile = async () => {     look launchImageLibrary({mediaType: 'mixed'}, result => {       if (!result.assets) {         Alarm.warning(issue.errorMessage);         render;       }       setAsset(result.assets[0]);     });   };    return (     <View style={styles.container}>       <TouchableOpacity onPress={selectFile}>         <Text fashion={styles.push}>SELECT {asset ? 'Another' : ''} FILE</Text>       </TouchableOpacity>       {asset ? (         asset.blazon.divide('/')[0] === 'paradigm' ? (           <Prototype             mode={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         ) : (           <Video             way={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         )       ) : nada}       {asset && (         <>           <TouchableOpacity onPress={() => setAsset(nil)}>             <Text manner={styles.cancelButton}>Remove Selected Image</Text>           </TouchableOpacity>         </>       )}     </View>   ); }  const styles = StyleSheet.create({   button: {     fontSize: twenty,     color: '#fff',     backgroundColor: 'blue',     paddingVertical: 20,     paddingHorizontal: xxx,     marginHorizontal: twenty,     marginVertical: 10,     textAlign: 'heart',     fontWeight: 'bold',   },   cancelButton: {     backgroundColor: '#fff',     color: 'blue',   },   selectedImage: {     width: 175,     height: 200,     marginTop: 20,   },   container: {     flex: one,     justifyContent: 'heart',     alignItems: 'heart',   }, });  export default S3StorageUpload;        

At present, run your mobile app in your device, simulator or emulator. You will observe that you at present are able to selection a photo or a video from your photo library.

iii. AWS Amplify Setup

Now that our mobile application UI is pretty much implemented, allow'southward focus on how to prepare the actual backend storage, and how we can integrate the mobile React Native app to communicate with the AWS backend, deeply and effectively.

a. Create A New AWS Dilate Project

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

react native s3 bucket

b. Install the AWS Amplify CLI

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

npm install -chiliad @aws-amplify/cli

This AWS Dilate CLI volition enable us run AWS commands anywhere on our local machine. For case, nosotros can update our local AWS configuration by pulling our AWS backend and updating our backend by 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 post-obit command at the root of your React Native projection:

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

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

c. Enable Storage in the AWS Dilate Project

At the root of your React Native project run dilate add storage to add together storage to your backend project every bit seen in the below screenshot. After that is washed y'all should push button your new projection configurations to the backend past running amplify push.

Note: On prompted you should select Content (Images, sound, video, etc.). Adding authentication or functions to your project is non mandatory and every other options tin exist left as their default value.

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

We've finally reached the core role of this tutorial. And then far, we set upwardly the React Native project, the AWS backend project, and we built the integration between these two. Nosotros've also implemented the ability for the users to pick photos from the gallery, so all we need to do at present is get those photos and send them over to the S3 deject.

a. Install aws-dilate Into the React Native Projection

yarn add together aws-amplify

or

npm install aws-amplify -South

b. And then Import AWS Dilate into Your App.js

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

and configure your AWS Dilate:

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

c. Add the following ii states to the S3StorageUpload

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

progressText will be used to brandish the progress of the upload and isLoading to help disable our buttons from performing any action while the epitome is getting uploaded.

d. Add together the following handler and helper functions

First we accept to convert our URI to a blobusing fetchResourceFromURI and then uploadResource uploads the file using the asset URI as the key.A success callback is passed to recall the primal of the uploaded file and this central is important because you need it to get the URI of the resources URI from the backend.

const fetchResourceFromURI = async uri => {   const response = expect fetch(uri);   console.log(response);   const blob = await response.hulk();   return blob; };  const uploadResource = async () => {   if (isLoading) return;   setisLoading(true);   const img = look fetchResourceFromURI(asset.uri);   return Storage.put(asset.uri, img, {     level: 'public',     contentType: nugget.type,     progressCallback(uploadProgress) {       setProgressText(         `Progress: ${Math.circular(           (uploadProgress.loaded / uploadProgress.total) * 100,         )} %`,       );       panel.log(         `Progress: ${uploadProgress.loaded}/${uploadProgress.total}`,       );     },   })     .then(res => {       setProgressText('Upload Done: 100%');       setAsset(nix);       setisLoading(simulated);       Storage.become(res.key)         .and then(upshot => console.log(effect))         .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

render (     <View fashion={styles.container}>       <TouchableOpacity onPress={selectFile}>         <Text style={styles.push button}>SELECT {asset ? 'Some other' : ''} FILE</Text>       </TouchableOpacity>       {asset ? (         nugget.type.separate('/')[0] === 'image' ? (           <Image             style={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         ) : (           <Video             style={styles.selectedImage}             source={{uri: asset?.uri ?? ''}}           />         )       ) : null}       {nugget && (         <>           <TouchableOpacity onPress={uploadResource}>             <Text style={styles.button}>UPLOAD</Text>           </TouchableOpacity>           <TouchableOpacity onPress={() => setAsset(null)}>             <Text style={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 function. Hither's a snippet short prune showing how this works.

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

Deleting a file is straightforward and can be done past a single function call that takes the file keyas a required parameters and an optional parameter protectedLevel that specifies the File Access Level of the file when it was uploaded

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

6. File Access Levels in AWS

At that place are 3 File Access Levels namely: public, protected, individual. The default level is public for instance when uploading a file using Storage.get('video.mp4') unless configured otherwise equally follows:

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

According to the official documentation:

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

  • Protected: Readable past all users, but writable only 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 accessible 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

You lot may get the following mistake when you run your app:Fault: jest-haste-map: Haste module naming collison:

To set this issue, simply delete theamplify/#electric current-deject-backend binder and re-build the app.

Determination

In this tutorial, nosotros have successfully been able to set up an AWS Amplify storage project in your AWS Amplify account, then nosotros configured it on your local machine and integrated it with the React Native project. Implementation wise, nosotros 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 deject, and too, we got familiar with the diverse privacy levels for the AWS file cloud.

If you want to skip the tutorial, and leap straight into the code, you tin can find the Github React Native AWS S3 Bucket project hither. If you lot constitute this helpful, please give u.s. a star on Github and share this article with your customs / your audition.

harrillsobsed1976.blogspot.com

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

0 Response to "Uploading Videos to S3 From React Native"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel