React Native Expo How to Upload Images to Firestore
In this tutorial, we will be building a Non-Expo React Native awarding to upload images and videos to Firebase deject storage. Firebase is a platform developed past Google used to create mobile and web applications. It was originally an independent company founded in 2011.
Firebase
In 2014, Google caused the platform and information technology is now 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 can utilise the cloud storage SDK to store images, audio, video, or other user-generated content.
Prerequisites
The fundamentals of React and React Native volition not exist covered in this tutorial. If you are not comfortable with the fundamentals, this is a helpful tutorial that you can go through before beginning with this projection.
Overview
We'll be going through these steps in this article:
- Development surroundings.
- Setting upwardly the Firebase project.
- Setting upwards Firebase storage.
- Installing dependencies.
- Building the UI.
- Adding media picker.
- Uploading media.
- Adding upload progress.
- Adding pause/resume upload.
- Get the download URL.
- Epitomize.
You can take a await at the final code in this GitHub Repository.
Development environs
IMPORTANT - We volition non exist using Expo in our project.
You can follow this documentation to fix the environment and create a new React app.
Make certain you're following the React Native CLI Quickstart, not the Expo CLI Quickstart.
Installing dependencies
You can install these in advance or while going through the article.
"@react-native-firebase/app" : "^10.iv.0" , "@react-native-firebase/storage" : "^10.4.0" , "react" : "xvi.xiii.1" , "react-native" : "0.63.4" , "react-native-image-picker" : "^iii.1.three" ,
To install a dependency, run:
npm i --salvage <package-name>
Later on installing the packages, for iOS, go into your ios/
directory, and run:
Of import FOR ANDROID
Every bit yous add more native dependencies to your project, information technology may bump you over the 64k method limit on the Android build system. Once you reach this limit, you will get-go to run into the following fault while attempting to build your Android application.
Execution failed for task ':app:mergeDexDebug'.
Apply this documentation to enable multidexing. To learn more about multidex, view the official Android documentation.
Setting up the Firebase projection
Head to the Firebase console and sign in to your account.
Create a new projection.
One time you create a new project, y'all'll see the dashboard.
At present, click on the Android icon to add an Android app to the Firebase project.
You will need the packet name of the application to register the application. You can find the parcel proper noun in the AndroidManifest.xml
that is located in android/app/src/master/
.
Once yous enter the package name and keep to the next step, you lot 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 access firebase services.
Afterward adding the file, go on to the side by side stride. Information technology will ask you to add some configurations to the build.gradle
files.
Kickoff, add together the google-services
plugin as a dependency within of your android/build.gradle
file:
buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google-services:4.three.three' } }
Then, execute the plugin by adding the post-obit to your android/app/build.gradle
file:
apply plugin: 'com.android.application' employ plugin: 'com.google.gms.google-services'
You demand to perform some additional steps to configure Firebase
for iOS
. Follow this documentation to fix it upwardly.
Finally, nosotros should install the @react-native-firebase/app
packet in our app to consummate the set for Firebase.
npm install @react-native-firebase/app
Setting up Firebase storage
Caput over to the Storage department in the dashboard and click on the Get Started
button.
A modal volition pop up with information about the storage rules. By default, just authenticated users tin read and write from the cloud storage. Since we are non going to cover hallmark in this tutorial, we will change the rules and set the cloud storage to open.
Do not gear up your cloud storage every bit open in a production awarding. This volition permit anyone to read and write to your cloud storage, compromising all the data in your deject storage.
On the adjacent step, it will inquire you lot for the storage bucket location.
One time this is done, you'll run across this screen. You can upload files and delete files manually from this screen.
Now, let'south edit the cloud storage rules and ready the deject storage bucket as open up
. Switch to the Rules
tab.
Now, supplant the existing rules with this.
rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if true; } } }
If you'd similar to learn more well-nigh cloud storage rules, refer here.
Building the UI
In the App.js
, permit'south add 4 buttons to the screen.
-
Take a Photo.
-
Record Video.
-
Pick a Photograph.
-
Pick a Video.
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; export default function App() { return ( <View fashion ={styles.screen}> <Text style ={styles.title}>Firebase Storage</Text> <View> <TouchableOpacity style ={styles.button}> <Text style ={styles.buttonText}>Take Photo</Text> </TouchableOpacity> <TouchableOpacity style ={styles.button}> <Text style ={styles.buttonText}>Tape Video</Text> </TouchableOpacity> <TouchableOpacity style ={styles.button}> <Text style ={styles.buttonText}>Pick a Photograph</Text> </TouchableOpacity> <TouchableOpacity style ={styles.button}> <Text style ={styles.buttonText}>Choice a Video</Text> </TouchableOpacity> </View> </View> ); }
Styles:
const styles = StyleSheet.create({ screen : { flex : 1, alignItems : 'heart', }, title : { fontSize : 35, marginVertical : 40, }, button : { backgroundColor : '#47477b', color : '#fff', justifyContent : 'middle', alignItems : 'heart', paddingVertical : 15, paddingHorizontal : forty, borderRadius : 50, marginTop : xx, }, buttonText : { colour : '#fff', }, });
Adding media picker
Now, the first ii buttons should open up the photographic camera to have a photo and record a video respectively, and the side by side two buttons should open the gallery to choice an image and video respectively.
Let's install the react-native-image-picker
to add these functionalities.
npm install react-native-image-picker
The minimum target SDK for the React Native Paradigm Picker is
21
. If your project targets an SDK beneath 21, bump up the minSDK target inandroid/build.gradle
.
Afterwards the parcel 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 kickoff statement is options
for the camera or the gallery, and the second argument is a callback function. This callback part is called when the user picks a media or cancels the operation.
Cheque out the API Reference for more details about these functions.
Now let's add 4 functions, 1 for each button.
const onTakePhoto = () => launchCamera({ mediaType : 'paradigm' }, onMediaSelect); const onTakeVideo = () => launchCamera({ mediaType : 'video' }, onMediaSelect); const onSelectImagePress = () => launchImageLibrary({ mediaType : 'image' }, onMediaSelect); const onSelectVideoPress = () => launchImageLibrary({ mediaType : 'video' }, onMediaSelect);
Let's create a function called onMediaSelect
. This is the callback function that we passed to the launchCamera
and the launchImageLibrary
functions. Nosotros volition go 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.
Nosotros should outset the upload process only when the user did not cancel the media picker. If the user cancelled the operation, the picker will transport a didCancel
property in the response object.
const onMediaSelect = async (media) => { if (! media.didCancel) { // Upload Process } };
You can learn more about the response object that we get from the launchCamera
and the launchImageLibrary
functions hither.
Now, pass the four functions to the onPress
prop of the TouchableOpacity
for the respective buttons.
For example:
<TouchableOpacity mode ={styles.push} onPress ={onTakePhoto}> <Text style ={styles.buttonText}>Take Photograph</Text> </TouchableOpacity>
Uploading media
Permit'south install the package for Firebase storage.
npm install @react-native-firebase/storage
Once the packet is installed, allow's import the package.
import storage from '@react-native-firebase/storage';
To upload a file to the cloud storage, nosotros should create a reference object.
A reference is a pointer to a file in your bucket. This file tin can either exist already, or it may not exist all the same.
Nosotros need to use the ref
method to create a reference.
const reference = storage().ref('<filename>');
You can also specify a file located in a nested directory:
const reference = storage().ref('/directory1/directory2/filename.png');
Now, we should employ the putFile
method in the reference
object to upload the paradigm from the user'due south 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 volition get 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 tin can accept a await at it in the Firebase console.
We don't have whatsoever visual feedback while the media is uploading. Let'due south add that in the next step.
Adding upload progress
The country of the Task
object that is returned from the putFile
method will keep changing while the file is getting uploaded. We can add an event handler to handle this state modify.
task.on('state_changed', (taskSnapshot) => { // Handle Event Here });
The callback function that we laissez passer will receive a TaskSnapshot
object. Information technology'll contain the number of bytes transferred and the full number of bytes of the file.
Nosotros can use this data to display the upload progress.
Let'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({});
Allow's set the uploading
state to true
when the onMediaSelect
is chosen.
const onMediaSelect = async (media) => { if (! media.didCancel) { setUploading(true); const reference = storage().ref(media.fileName);
Now, nosotros need to set the TaskSnapshot
object on the state_changed
event handler.
task.on('state_changed', (taskSnapshot) => { setUploadTaskSnapshot(taskSnapshot); });
Let'southward display the progress in the UI using these states along with an action indicator and a status text. This should exist displayed only when a file is existence uploaded.
import { ActivityIndicator } from 'react-native';
{uploading && ( <View fashion ={styles.uploading}> <ActivityIndicator size ={threescore} colour = "#47477b"></ActivityIndicator> <Text style ={styles.statusText}>Uploading</Text> <Text style ={styles.statusText}> {` ${((uploadTaskSnapshot.bytesTransferred / uploadTaskSnapshot.totalBytes) * 100).toFixed(ii)} % / 100%`} </Text> </View> )}
Styles:
center : { flex : 1, width : '100%', justifyContent : 'center', alignItems : 'centre', paddingHorizontal : l, }, uploading : { marginTop : 80, justifyContent : 'heart', alignItems : 'center', }, statusText : { marginTop : 20, fontSize : 20, },
Calculation pause/resume upload
Let'due south add a state to maintain whether the upload is paused or not. This will be a boolean country.
const [paused, setPaused] = useState(fake);
Let'south add a push to Pause/Resume the upload when a file is existence uploaded.
{uploading && ( <View style ={styles.uploading}> <ActivityIndicator size ={sixty} colour = "#47477b"></ActivityIndicator> <Text mode ={styles.statusText}>Uploading</Text> <Text manner ={styles.statusText}> {` ${((uploadTaskSnapshot.bytesTransferred / uploadTaskSnapshot.totalBytes) * 100).toFixed(2)} % / 100%`} </Text> <TouchableOpacity manner ={styles.button}> <Text style ={styles.buttonText}>{paused ? 'Resume' : 'Pause'}</Text> </TouchableOpacity> </View> )}
To pause/resume the upload, we need to employ the Task
object. It has two methods: break
and resume
. Since the task object is within the onMediaSelect
role, permit's gear up up a country outside and assign the Task
object to that state when information technology'south created.
const [uploadTask, setUploadTask] = useState(); const onMediaSelect = async (media) => { if (! media.didCancel) { setUploading(true); const reference = storage().ref(media.fileName); const chore = reference.putFile(media.uri); setUploadTask(job);
Now, nosotros tin write a function to toggle between pause and resume.
const togglePause = () => { if (paused) uploadTask.resume(); else uploadTask.intermission(); setPaused((paused) => ! paused); };
Pass this part to the onPress
laissez passer of the break button.
<TouchableOpacity fashion ={styles.button} onPress ={togglePause}> <Text style ={styles.buttonText}>{paused ? 'Resume' : 'Pause'}</Text> </TouchableOpacity>
Let's update the status text to paused and hibernate the activity indicator if the upload is paused.
{! paused && <ActivityIndicator size ={lx} color = "#47477b"></ActivityIndicator>} <Text fashion ={styles.statusText}> {paused ? 'Paused' : 'Uploading'} </Text>
Get the download URL
The putFile
method returns a Job object.
We tin can add a .and then()
to it that will get called when the upload is completed. If not, the .catch()
volition be called.
const onMediaSelect = async (media) => { const reference = storage().ref(media.fileName); const job = reference.putFile(media.uri); task.and so(async () => { // Get Download URL Hither }); };
We tin can go the download URL using the reference to the storage location.
task.then(async () => { const downloadURL = wait reference.getDownloadURL(); });
Let's create a button that volition open the link in your phone's browser.
To do so, permit'due south create a country to store the download URL and admission it outside this function.
const [downloadURL, setDownloadURL] = useState();
Let'south ready the URL once we get information technology.
task.so(async () => { const downloadURL = reference.getDownloadURL(); setDownloadURL(downloadURL); });
Now, let's create a button in the UI. This button volition just be displayed when a download URL is available.
{downloadURL && ( <TouchableOpacity mode ={[styles.button, style.mediaButton]}> <Text style ={styles.buttonText}>View Media</Text> </TouchableOpacity> )}
Styles:
mediaButton : { position : 'absolute', bottom : 0, marginBottom : fifty, width : 300, },
We need to use the Linking
module from react-native
to open up the link in the phone's browser. Let's import it.
import { Linking } from 'react-native';
To open the link, we should utilize the openURL
method in the Linking
module.
<TouchableOpacity style ={[styles.button, styles.mediaButton]} onPress ={() => Linking.openURL(downloadURL)}> <Text fashion ={styles.buttonText}>View Media</Text> </TouchableOpacity>
Now, the button should open the media that nosotros uploaded on the telephone's browser.
Permit's Recap
-
We gear up upwardly our development surround and created a React Native app.
-
We created a Firebase project.
-
Nosotros set up deject storage for our Firebase projection.
-
Nosotros updated the cloud storage rules to be open up for anybody. Keep in mind that you should never keep it open in a production surroundings.
-
We built a elementary UI for the app.
-
We added the
react-native-image-picker
package to pick images/videos using the gallery and capture images/video using the camera. -
We installed the Firebase cloud storage parcel.
-
Nosotros created a deject storage reference using the
ref
part. -
Nosotros uploaded our file to the location which was existence pointed past the reference we created.
-
Nosotros added an event handler for the
state_changed
event during upload and used theTaskSnapshot
object to get the upload progress. -
We added a button to interruption/resume the upload.
-
Nosotros got the download URL from the reference and added a button to open it in the telephone'due south browser.
Congratulations, 🥳 You did it.
Cheers for Reading!
Peer Review Contributions by: Michael Barasa
Source: https://www.section.io/engineering-education/react-native-firebase-storage/
0 Response to "React Native Expo How to Upload Images to Firestore"
إرسال تعليق