How to Upload File to Amazon Public Writable Bucket S3
Mega Packet Sale is ON! Get ALL of our React Native codebases at 80% OFF discount 🔥
In this tutorial nosotros will build a React Native app that allows users to upload images and videos from their camera and photo library straight into a AWS S3 bucket. As AWS is the leader of deject providers, a huge function of the React Native ecosystem is using AWS every bit the backend for their app. With the release of AWS Amplify, using AWS equally 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 shop image and video files using Amazon S3 bucket. In this article, we will teach yous how image and video storage works in React Native using AWS S3 bucket. Every single step of the implementation will be detailed and no stones volition be left unturned. So allow the states get into it.
For those who are non 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 store an object in Amazon S3, you upload the file you desire to store to a bucket. When you upload a file, you can set permissions on the object and any metadata.
one. Creating the React Native Projection
Open a new Last instance, 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-epitome-picker react-native-video @react-native-community/netinfo @react-native-async-storage/async-storage -Southward
For iOS you also need to install the pods by running
cd ios && pod install
Then add the post-obit snippet to your ios/<projectName>/Info.plist to request Photograph Library permissions.
<central>NSPhotoLibraryUsageDescription</fundamental> <string>$(PRODUCT_NAME) would similar access to your photo gallery.</string>
two. Picking Photos & Videos from Photo Library
Our first task here is to fetch an image or video from the user's photo library. In club to accomplish that, we are going to leveragereact-native-prototype-picker to option media files from the library. To be able to brandish and play videos, nosotros are as well going to use the npm packagereact-native-video. Now, let's supercede all yourApp.js file with the following source lawmaking:
import React, {useState} from 'react'; import { View, Text, TouchableOpacity, StyleSheet, Alarm, Image, } from 'react-native'; import {launchImageLibrary} from 'react-native-paradigm-picker'; import Video from 'react-native-video'; function S3StorageUpload() { const [nugget, setAsset] = useState(aught); const selectFile = async () => { await launchImageLibrary({mediaType: 'mixed'}, issue => { if (!result.avails) { Alert.alert(upshot.errorMessage); return; } setAsset(result.avails[0]); }); }; return ( <View style={styles.container}> <TouchableOpacity onPress={selectFile}> <Text style={styles.button}>SELECT {asset ? 'ANOTHER' : ''} FILE</Text> </TouchableOpacity> {asset ? ( nugget.blazon.dissever('/')[0] === 'image' ? ( <Image way={styles.selectedImage} source={{uri: asset?.uri ?? ''}} /> ) : ( <Video style={styles.selectedImage} source={{uri: asset?.uri ?? ''}} /> ) ) : nil} {asset && ( <> <TouchableOpacity onPress={() => setAsset(goose egg)}> <Text style={styles.cancelButton}>Remove Selected Image</Text> </TouchableOpacity> </> )} </View> ); } const styles = StyleSheet.create({ button: { fontSize: twenty, color: '#fff', backgroundColor: 'blueish', paddingVertical: 20, paddingHorizontal: 30, marginHorizontal: xx, marginVertical: 10, textAlign: 'center', fontWeight: 'bold', }, cancelButton: { backgroundColor: '#fff', color: 'blue', }, selectedImage: { width: 175, height: 200, marginTop: 20, }, container: { flex: 1, justifyContent: 'middle', alignItems: 'center', }, }); consign default S3StorageUpload; Now, run your mobile app in your device, simulator or emulator. You will notice that yous now are able to pick a photo or a video from your photograph library.
3. AWS Dilate Setup
At present that our mobile awarding UI is pretty much implemented, let'southward focus on how to set up the bodily backend storage, and how we can integrate the mobile React Native app to communicate with the AWS backend, securely and effectively.
a. Create A New AWS Amplify Project
Head over to the AWS website and create a new AWS Dilate project.
b. Install the AWS Amplify CLI
Side by side, nosotros demand to install AWS Amplify CLI on our local motorcar by running the following command on your terminal.
npm install -g @aws-amplify/cli
This AWS Amplify CLI volition enable united states run AWS commands anywhere on our local machine. For example, we can update our local AWS configuration past pulling our AWS backend and updating our backend past pushing local configuration changes to the backend.
c. Pull The AWS Amplify Projection into the React Native Codebase
Pull your already created Dilate 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: Please be sure to verify the app login on your Amplify UI Admin, then select your preferred editor, type of app as Javascript, and framework every bit React Native. You lot 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 Amplify Projection
At the root of your React Native project run amplify add storage to add storage to your backend projection every bit seen in the below screenshot. Later that is done you should button your new projection configurations to the backend by running dilate push.
Notation: On prompted you should select Content (Images, sound, video, etc.). Adding hallmark or functions to your project is not mandatory and every other options can be left as their default value.
three. Upload Photos & Videos to AWS S3 Bucket in React Native
We've finally reached the core part of this tutorial. And so far, we set upwards the React Native project, the AWS backend projection, and nosotros built the integration betwixt these two. We've also implemented the power for the users to selection photos from the gallery, so all nosotros need to do now is get those photos and transport them over to the S3 deject.
a. Install aws-amplify Into the React Native Project
yarn add aws-amplify
or
npm install aws-dilate -S
b. Then 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 the following two states to the S3StorageUpload
const [progressText, setProgressText] = useState(''); const [isLoading, setisLoading] = useState(false); progressText will be used to display the progress of the upload and isLoading to help disable our buttons from performing whatsoever action while the image is getting uploaded.
d. Add the following handler and helper functions
First we accept to catechumen our URI to a hulkusing fetchResourceFromURI then uploadResource uploads the file using the asset URI as the fundamental.A success callback is passed to retrieve the fundamental of the uploaded file and this central is important because you need it to go the URI of the resource URI from the backend.
const fetchResourceFromURI = async uri => { const response = await fetch(uri); console.log(response); const blob = await response.hulk(); return hulk; }; const uploadResource = async () => { if (isLoading) render; setisLoading(true); const img = expect fetchResourceFromURI(asset.uri); return Storage.put(asset.uri, img, { level: 'public', contentType: asset.type, progressCallback(uploadProgress) { setProgressText( `Progress: ${Math.round( (uploadProgress.loaded / uploadProgress.full) * 100, )} %`, ); console.log( `Progress: ${uploadProgress.loaded}/${uploadProgress.total}`, ); }, }) .and so(res => { setProgressText('Upload Done: 100%'); setAsset(zip); setisLoading(false); Storage.get(res.central) .then(result => console.log(result)) .catch(err => { setProgressText('Upload Fault'); panel.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 style={styles.button}>SELECT {nugget ? 'ANOTHER' : ''} FILE</Text> </TouchableOpacity> {asset ? ( asset.type.split('/')[0] === 'epitome' ? ( <Image style={styles.selectedImage} source={{uri: nugget?.uri ?? ''}} /> ) : ( <Video mode={styles.selectedImage} source={{uri: asset?.uri ?? ''}} /> ) ) : null} {asset && ( <> <TouchableOpacity onPress={uploadResource}> <Text mode={styles.push}>UPLOAD</Text> </TouchableOpacity> <TouchableOpacity onPress={() => setAsset(null)}> <Text style={styles.cancelButton}>Remove Selected Prototype</Text> </TouchableOpacity> </> )} <Text>{progressText}</Text> </View> ); In the above snippet nosotros edit and update the UI past adding a button to trigger the uploadResource part. Here's a snippet short clip showing how this works.
v. Deleting a File from AWS S3 Bucket in React Native
Deleting a file is straightforward and can be done by a single office 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 Admission Levels in AWS
There are 3 File Admission Levels namely: public, protected, private. The default level is public for instance when uploading a file using Storage.become('video.mp4') unless configured otherwise as follows:
Storage.configure({ level: 'individual' }); According to the official documentation:
-
Public: Accessible past all users of your app. Files are stored under the
public/path in your S3 saucepan. -
Protected: Readable by all users, but writable only past the creating user. Files are stored under
protected/{user_identity_id}/where theuser_identity_idcorresponds to the unique Amazon Cognito Identity ID for that user. -
Individual: Only accessible for the private user. Files are stored nether
individual/{user_identity_id}/where theuser_identity_idcorresponds to the unique Amazon Cognito Identity ID for that user.
Notation
You may become the following error when yous run your app:Fault: jest-haste-map: Haste module naming collison:
To ready this result, simply delete theamplify/#electric current-deject-backend binder and re-build the app.
Conclusion
In this tutorial, we accept successfully been able to set upwards an AWS Amplify storage projection in your AWS Dilate account, then we configured information technology on your local machine and integrated it with the React Native projection. Implementation wise, nosotros built a feature that allows the users to pick photos and videos from their photograph gallery and upload it to the S3 bucket deject. We've too learned how to remove those files from the cloud, and too, we got familiar with the various privacy levels for the AWS file cloud.
If yous want to skip the tutorial, and jump straight into the lawmaking, y'all can find the Github React Native AWS S3 Bucket project here. If you found this helpful, please give us a star on Github and share this article with your community / your audience.
Source: https://instamobile.io/react-native-tutorials/react-native-aws-s3/
0 Response to "How to Upload File to Amazon Public Writable Bucket S3"
Post a Comment