How To Upload Image To Firebase Storage React Native
In this tutorial, we volition be edifice a Non-Expo React Native awarding to upload images and videos to Firebase cloud storage. Firebase is a platform developed by Google used to create mobile and web applications. It was originally an independent visitor founded in 2011.
Firebase
In 2014, Google caused the platform and it is at present their flagship offering for app development. Deject Storage for Firebase is a powerful and toll-effective storage service. The Cloud Storage SDK supports file uploads and downloads for your apps. You tin can apply the deject storage SDK to store images, audio, video, or other user-generated content.
Prerequisites
The fundamentals of React and React Native will not exist covered in this tutorial. If you are non comfortable with the fundamentals, this is a helpful tutorial that y'all tin can go through before beginning with this project.
Overview
We'll be going through these steps in this commodity:
- Evolution environs.
- Setting up the Firebase projection.
- Setting up Firebase storage.
- Installing dependencies.
- Edifice the UI.
- Calculation media picker.
- Uploading media.
- Adding upload progress.
- Calculation break/resume upload.
- Get the download URL.
- Recap.
Yous can take a look at the final lawmaking in this GitHub Repository.
Evolution environment
IMPORTANT - Nosotros will not be using Expo in our project.
You tin follow this documentation to ready the environment and create a new React app.
Brand sure you lot're post-obit the React Native CLI Quickstart, not the Expo CLI Quickstart.
Installing dependencies
You lot can install these in accelerate or while going through the article.
"@react-native-firebase/app" : "^10.iv.0" , "@react-native-firebase/storage" : "^10.iv.0" , "react" : "16.13.ane" , "react-native" : "0.63.4" , "react-native-image-picker" : "^3.1.3" , To install a dependency, run:
npm i --salvage <package-proper name> After installing the packages, for iOS, go into your ios/ directory, and run:
IMPORTANT FOR ANDROID
As you lot add together more native dependencies to your project, information technology may bump you over the 64k method limit on the Android build arrangement. Once you attain this limit, you will start to see the following mistake while attempting to build your Android application.
Execution failed for task ':app:mergeDexDebug'.Use this documentation to enable multidexing. To learn more than nearly multidex, view the official Android documentation.
Setting upwards the Firebase project
Head to the Firebase console and sign in to your account.
Create a new projection.
One time you create a new project, you'll see the dashboard.
Now, click on the Android icon to add an Android app to the Firebase project.
You will need the parcel name of the awarding to annals the application. You lot tin can find the bundle proper name in the AndroidManifest.xml that is located in android/app/src/principal/.
Once you enter the parcel name and continue to the next footstep, y'all tin can download the google-services.json file. You should place this file in the android/app directory.
This file contains configurations that'll enable your application to admission firebase services.
Later calculation the file, proceed to the next footstep. Information technology will ask you to add some configurations to the build.gradle files.
First, add the google-services plugin equally a dependency inside of your android/build.gradle file:
buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google-services:4.3.3' } } Then, execute the plugin by adding the following to your android/app/build.gradle file:
employ plugin: 'com.android.awarding' apply plugin: 'com.google.gms.google-services' You need to perform some additional steps to configure Firebase for iOS. Follow this documentation to ready it upward.
Finally, we should install the @react-native-firebase/app package in our app to complete the set up for Firebase.
npm install @react-native-firebase/app Setting upwards Firebase storage
Head over to the Storage section in the dashboard and click on the Get Started button.
A modal will popular up with information about the storage rules. By default, but authenticated users can read and write from the cloud storage. Since we are non going to cover hallmark in this tutorial, nosotros will change the rules and gear up the deject storage to open.
Do non set your cloud storage as open in a production application. This will allow anyone to read and write to your cloud storage, compromising all the data in your deject storage.
On the next step, it volition ask you lot for the storage bucket location.
Once this is done, you'll see this screen. You tin can upload files and delete files manually from this screen.
Now, permit's edit the cloud storage rules and set the deject storage saucepan as open. Switch to the Rules tab.
Now, replace the existing rules with this.
rules_version = 'ii'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { permit read, write: if true; } } } If you lot'd similar to larn more about deject storage rules, refer hither.
Building the UI
In the App.js, let's add iv buttons to the screen.
-
Accept a Photo.
-
Record Video.
-
Pick a Photo.
-
Pick a Video.
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; export default function App() { return ( <View style ={styles.screen}> <Text style ={styles.title}>Firebase Storage</Text> <View> <TouchableOpacity way ={styles.button}> <Text style ={styles.buttonText}>Take Photo</Text> </TouchableOpacity> <TouchableOpacity style ={styles.button}> <Text fashion ={styles.buttonText}>Record Video</Text> </TouchableOpacity> <TouchableOpacity manner ={styles.button}> <Text style ={styles.buttonText}>Choice a Photo</Text> </TouchableOpacity> <TouchableOpacity mode ={styles.button}> <Text style ={styles.buttonText}>Choice a Video</Text> </TouchableOpacity> </View> </View> ); } Styles:
const styles = StyleSheet.create({ screen : { flex : 1, alignItems : 'middle', }, championship : { fontSize : 35, marginVertical : xl, }, push button : { backgroundColor : '#47477b', color : '#fff', justifyContent : 'centre', alignItems : 'center', paddingVertical : 15, paddingHorizontal : 40, borderRadius : 50, marginTop : twenty, }, buttonText : { colour : '#fff', }, });
Calculation media picker
Now, the first 2 buttons should open the photographic camera to take a photo and record a video respectively, and the next 2 buttons should open the gallery to pick an image and video respectively.
Let'south install the react-native-image-picker to add together these functionalities.
npm install react-native-image-picker The minimum target SDK for the React Native Image Picker is
21. If your project targets an SDK beneath 21, bump up the minSDK target inandroid/build.gradle.
Subsequently the bundle is installed, import the launchCamera and launchImageLibrary functions from the package.
import { launchCamera, launchImageLibrary } from 'react-native-image-picker'; Both functions accept 2 arguments. The starting time statement is options for the camera or the gallery, and the second statement is a callback part. This callback function is called when the user picks a media or cancels the operation.
Check out the API Reference for more details virtually these functions.
At present allow'south add together 4 functions, one for each button.
const onTakePhoto = () => launchCamera({ mediaType : 'image' }, onMediaSelect); const onTakeVideo = () => launchCamera({ mediaType : 'video' }, onMediaSelect); const onSelectImagePress = () => launchImageLibrary({ mediaType : 'prototype' }, onMediaSelect); const onSelectVideoPress = () => launchImageLibrary({ mediaType : 'video' }, onMediaSelect); Let'due south create a office called onMediaSelect. This is the callback function that we passed to the launchCamera and the launchImageLibrary functions. We will get the details of the media that the user picked in this callback function. We'll use that to upload the media to the deject storage.
We should start the upload process merely when the user did not cancel the media picker. If the user cancelled the operation, the picker will send a didCancel property in the response object.
const onMediaSelect = async (media) => { if (! media.didCancel) { // Upload Process } }; You tin acquire more about the response object that nosotros get from the launchCamera and the launchImageLibrary functions hither.
Now, laissez passer the 4 functions to the onPress prop of the TouchableOpacity for the respective buttons.
For example:
<TouchableOpacity way ={styles.button} onPress ={onTakePhoto}> <Text style ={styles.buttonText}>Take Photo</Text> </TouchableOpacity> Uploading media
Allow'southward install the parcel for Firebase storage.
npm install @react-native-firebase/storage Once the package is installed, let'southward import the package.
import storage from '@react-native-firebase/storage'; To upload a file to the cloud storage, we should create a reference object.
A reference is a pointer to a file in your saucepan. This file tin can either exist already, or information technology may not exist yet.
Nosotros need to use the ref method to create a reference.
const reference = storage().ref('<filename>'); Y'all can also specify a file located in a nested directory:
const reference = storage().ref('/directory1/directory2/filename.png'); Now, we should use the putFile method in the reference object to upload the image from the user'southward device to the cloud storage. The putFile method accepts a path to the file on the user's device.
The callback function that we passed to launchCamera and the launchImageLibrary functions will become the URI of the prototype in the response object. We need to pass the URI to the putFile method.
const onMediaSelect = async (media) => { if (! media.didCancel) { const reference = storage().ref(media.fileName); const task = reference.putFile(media.uri); } }; Once the media has been uploaded, you can take a look at it in the Firebase console.
We don't have any visual feedback while the media is uploading. Let's add that in the next pace.
Adding upload progress
The state of the Task object that is returned from the putFile method will keep changing while the file is getting uploaded. We can add an consequence handler to handle this land change.
chore.on('state_changed', (taskSnapshot) => { // Handle Outcome Here }); The callback function that nosotros laissez passer will receive a TaskSnapshot object. It'll contain the number of bytes transferred and the total number of bytes of the file.
We tin can use this information to display the upload progress.
Permit's create 2 states in the application: One to maintain whether the file is getting uploaded and the other for the TaskSnapshot object.
const [uploading, setUploading] = useState(false); const [uploadTaskSnapshot, setUploadTaskSnapshot] = useState({}); Let's set the uploading state to true when the onMediaSelect is called.
const onMediaSelect = async (media) => { if (! media.didCancel) { setUploading(true); const reference = storage().ref(media.fileName); Now, we demand to set the TaskSnapshot object on the state_changed event handler.
task.on('state_changed', (taskSnapshot) => { setUploadTaskSnapshot(taskSnapshot); }); Allow's brandish the progress in the UI using these states along with an activity indicator and a status text. This should exist displayed but when a file is being uploaded.
import { ActivityIndicator } from 'react-native'; {uploading && ( <View way ={styles.uploading}> <ActivityIndicator size ={60} colour = "#47477b"></ActivityIndicator> <Text fashion ={styles.statusText}>Uploading</Text> <Text mode ={styles.statusText}> {` ${((uploadTaskSnapshot.bytesTransferred / uploadTaskSnapshot.totalBytes) * 100).toFixed(2)} % / 100%`} </Text> </View> )} Styles:
heart : { flex : 1, width : '100%', justifyContent : 'center', alignItems : 'center', paddingHorizontal : 50, }, uploading : { marginTop : lxxx, justifyContent : 'heart', alignItems : 'center', }, statusText : { marginTop : twenty, fontSize : 20, },
Calculation break/resume upload
Let's add a land to maintain whether the upload is paused or not. This will be a boolean state.
const [paused, setPaused] = useState(false); Let's add a button to Pause/Resume the upload when a file is being uploaded.
{uploading && ( <View style ={styles.uploading}> <ActivityIndicator size ={60} color = "#47477b"></ActivityIndicator> <Text style ={styles.statusText}>Uploading</Text> <Text way ={styles.statusText}> {` ${((uploadTaskSnapshot.bytesTransferred / uploadTaskSnapshot.totalBytes) * 100).toFixed(two)} % / 100%`} </Text> <TouchableOpacity style ={styles.push}> <Text style ={styles.buttonText}>{paused ? 'Resume' : 'Pause'}</Text> </TouchableOpacity> </View> )}
To pause/resume the upload, we need to apply the Task object. It has 2 methods: pause and resume. Since the task object is inside the onMediaSelect office, let's prepare up a state outside and assign the Task object to that state when it'south created.
const [uploadTask, setUploadTask] = useState(); const onMediaSelect = async (media) => { if (! media.didCancel) { setUploading(true); const reference = storage().ref(media.fileName); const task = reference.putFile(media.uri); setUploadTask(chore); Now, we tin can write a function to toggle betwixt pause and resume.
const togglePause = () => { if (paused) uploadTask.resume(); else uploadTask.suspension(); setPaused((paused) => ! paused); }; Pass this function to the onPress laissez passer of the pause push.
<TouchableOpacity style ={styles.push} onPress ={togglePause}> <Text style ={styles.buttonText}>{paused ? 'Resume' : 'Interruption'}</Text> </TouchableOpacity> Let'due south update the status text to paused and hide the action indicator if the upload is paused.
{! paused && <ActivityIndicator size ={60} colour = "#47477b"></ActivityIndicator>} <Text style ={styles.statusText}> {paused ? 'Paused' : 'Uploading'} </Text>
Become the download URL
The putFile method returns a Job object.
We can add together a .then() to it that will get chosen when the upload is completed. If not, the .take hold of() will exist called.
const onMediaSelect = async (media) => { const reference = storage().ref(media.fileName); const task = reference.putFile(media.uri); task.then(async () => { // Go Download URL Hither }); }; We can get the download URL using the reference to the storage location.
task.then(async () => { const downloadURL = await reference.getDownloadURL(); }); Allow'due south create a button that will open the link in your phone's browser.
To do so, let'due south create a country to store the download URL and admission information technology outside this office.
const [downloadURL, setDownloadURL] = useState(); Allow's set the URL once we get information technology.
task.then(async () => { const downloadURL = reference.getDownloadURL(); setDownloadURL(downloadURL); }); Now, permit'south create a push button in the UI. This button will merely exist displayed when a download URL is available.
{downloadURL && ( <TouchableOpacity style ={[styles.button, style.mediaButton]}> <Text mode ={styles.buttonText}>View Media</Text> </TouchableOpacity> )} Styles:
mediaButton : { position : 'absolute', lesser : 0, marginBottom : 50, width : 300, }, We demand to apply the Linking module from react-native to open the link in the telephone'south browser. Let's import it.
import { Linking } from 'react-native'; To open the link, we should utilise the openURL method in the Linking module.
<TouchableOpacity way ={[styles.push button, styles.mediaButton]} onPress ={() => Linking.openURL(downloadURL)}> <Text style ={styles.buttonText}>View Media</Text> </TouchableOpacity> Now, the button should open the media that we uploaded on the phone's browser.
Allow's Recap
-
Nosotros set our development environment and created a React Native app.
-
Nosotros created a Firebase project.
-
We set cloud storage for our Firebase project.
-
We updated the cloud storage rules to be open for everyone. Keep in mind that you lot should never keep it open in a production environment.
-
We built a simple UI for the app.
-
We added the
react-native-image-pickerpackage to pick images/videos using the gallery and capture images/video using the camera. -
We installed the Firebase cloud storage parcel.
-
Nosotros created a cloud storage reference using the
reffunction. -
Nosotros uploaded our file to the location which was beingness pointed by the reference nosotros created.
-
We added an outcome handler for the
state_changedevent during upload and used theTaskSnapshotobject to become the upload progress. -
We added a button to pause/resume the upload.
-
We got the download URL from the reference and added a button to open it in the phone's browser.
Congratulations, 🥳 You lot did it.
Thanks for Reading!
Peer Review Contributions by: Michael Barasa
Source: https://www.section.io/engineering-education/react-native-firebase-storage/
Posted by: schultzhenceld68.blogspot.com

0 Response to "How To Upload Image To Firebase Storage React Native"
Post a Comment