Firebase is a popular tool that helps you build apps fast, without managing infrastructure. It offers lots of services to help your app grow such as Hosting, Storage, Database, Authentication and much more. It's built on top of Google infrastructure and can scale automatically, so you don't have to worry about scaling your own servers.
In this Ionic Framework tutorial I'll show you how to upload an image from an Ionic App to Firebase Cloud Storage.
Cloud Storage is built for app developers who need to store and serve user-generated content, such as photos, videos or files. Cloud Storage stores your files in a Google Cloud Storage bucket, making them accessible through both Firebase and Google Cloud. This allows you the flexibility to upload and download files from mobile clients via the Firebase SDKs, and do server-side processing such as image filtering or video transcoding using Google Cloud Platform.
Handling images and files is super useful if you want to build rich media content into your apps. For example you could use it to store pictures or videos uploaded to your app by your users. If you learn how to create an Ionic application with Firebase you will be able to build a complete mobile app integrated with Firebase.
In this Ionic tutorial we will use three plugins:
- AngularFire for the communication between Ionic and Firebase.
- Image Picker to retrieve images from the phone's image gallery.
- Crop to allow users to crop an image once it has been selected from the image gallery.
Let's start with an Ionic app. You can either download the free Ionic example app we built for this tutorial by clicking in the "GET THE CODE" button from above or you can create your own Ionic app from scratch. To learn more about how to start with Ionic Framework check Ionic Framework introduction and key components.
To install the plugins mentioned before, we need to run the following commands in our development console.
AngularFire plugin:
npm install firebase @angular/fire --save
Ionic ImagePicker plugin:
ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="your usage message"
npm install --save @ionic-native/image-picker
Ionic Crop plugin:
ionic cordova plugin add cordova-plugin-cropnpm install --save @ionic-native/crop
Once the plugins are installed we need to create a Firebase project (which is free). To do this we have to go to the Firebase console, and follow the steps to create a new project.
Then, enter to your new project dashboard and you will see something like this:
Click on "Add Firebase to your web app" to see the credentials of your new Firebase application. We’re going to use these credentials in our Ionic project.
Your credentials will look similar to this:
The next step is to paste these credentials in our Ionic project. Because we are building an Ionic Angular project, we can use the environment.ts
file, located at src/environment/
. A project's src/environments/
folder contains the base configuration file, environment.ts
, which provides a default environment.
You can add override defaults for additional environments, such as production
and staging
, in target-specific configuration files.
export const environment = { production: false, firebase: { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", databaseURL: "YOUR_DATABASE_URL", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_SENDER_ID" } };
Please note that you need to replace the constants from above with your own credentials.
In Ionic 6 Full Starter App - PRO version you will find a ready-made example of how to use Firebase in a real Ionic Framework app. Using a template like this will save you tons of development and design hours and will give your app a proffesional look and feel.
This Ionic Firebase Starter App includes Firebase Authentication and an advanced Firebase CRUD integration with search filters and nested relations.
Congratulations! We finished with the installation part. Now we’re ready to move on to the implementation of our Ionic app.
For this tutorial, we created a super simple app with two buttons: one to pick an image from the image gallery and save it to the Firebase database and the other one, with the additional feature that allows to crop the image (using the Crop plugin) and then save it to Firebase.
In order to perform the operations related to the interaction with the Firebase database, we will create a service in our Ionic app that we'll name FirebaseService
.
In this service we will create a uploadImage
method that will receive the URI
provided to us by the ImagePicker
plugin and we will save the image to Firebase Storage.
uploadImage(imageURI) { return new Promise<any>((resolve, reject) => { let storageRef = firebase.storage().ref(); let imageRef = storageRef.child('image').child('imageName'); this.encodeImageUri(imageURI, function(image64) { imageRef.putString(image64, 'data_url') .then(snapshot => { resolve(snapshot.downloadURL) }, err => { reject(err); }) }) }) }
Firebase Storage is a tool provided by Firebase to save files. It's independent from both Firebase Realtime database and Firestore.
Let's see what we are doing inside the uploadImage
function:
storageRef
represents a reference to the Storage root.imageRef
is the reference to a Storage lower-tier location, used by thechild()
method in a specific reference. That's why the images we upload to Firebase will be stored in theimage
folder.encodeImageUri()
is a function we'll explain below that is used to transform a URI into a base64 URL.imageRef.putString()
is the function to upload the base64 URL string to the storage. Once our Firebase image is uploaded it returns the target URL of the uploaded image.
We need to transform the URI into a base64 URL so we created the following function encodeImageUri
that does exactly this. Then, we invoke this function from the previous uploadImage()
.
encodeImageUri(imageUri, callback) { var c = document.createElement('canvas'); var ctx = c.getContext("2d"); var img = new Image(); img.onload = function () { var aux:any = this; c.width = aux.width; c.height = aux.height; ctx.drawImage(img, 0, 0); var dataURL = c.toDataURL("image/jpeg"); callback(dataURL); }; img.src = imageUri; };
Now let's see how to use the previous code to upload the images. We will see what happens when clicking our buttons from our super simple Ionic example app.
Let's start with the function to select an image from the device gallery but without using the option to crop it:
openImagePicker() { this.imagePicker.hasReadPermission() .then(result => { if (result === false) { this.imagePicker.requestReadPermission(); } else if (result === true) { this.imagePicker.getPictures({ // the amout of images that the user can select maximumImagesCount: 1 }).then(results => { for (var i = 0; i < results.length; i++) { this.uploadImageToFirebase(results[i]); } }, err => console.log(err)); } }, err => console.log(err)); }
As we can see, the result of the imagePicker
plugin is a list of images that can be limited by the maximumImagesCount
property. In this example the limit is just one picture.
Once the image is selected, another function is called and it interacts with our FirebaseService
to upload the image to Firebase Storage.
uploadImageToFirebase(image) { image = normalizeURL(image); // uploads image to firebase storage this.firebaseService.uploadImage(image) .then(photoURL => { let toast = this.toastCtrl.create({ message: 'Image was updated successfully', duration: 3000 }); toast.present(); }) }
normalizeURL
is a method used to normalize the absolute URL of the image so that it works in every device. You can read more about this method right here.
Well done! You've just learned how to upload an image to Firebase Storage from an Ionic app. Now if you log in to your Firebase Console, you can verify your image has been correctly uploaded to your folder.
Now let's see how to use the Crop plugin. The Ionic Crop plugin allows us to easily crop an image from our Ionic framework app.
The code is very simple and similar to the previous step, the difference is that once the image is selected using the Image Picker plugin, we use the crop plugin, which returns the cropped image that we'll upload to Storage.
openImagePickerCrop(){ this.imagePicker.hasReadPermission().then( (result) => { if(result === false){ // no callbacks required as this opens a popup which returns async this.imagePicker.requestReadPermission(); } else if(result === true){ this.imagePicker.getPictures({ maximumImagesCount: 1 }).then( (results) => { for (var i = 0; i < results.length; i++) { this.cropService.crop(results[i], {quality: 75}).then( newImage => { this.uploadImageToFirebase(newImage); }, error => console.error("Error cropping image", error) ); } }, (err) => console.log(err) ); } }, (err) => { console.log(err); }); }
In this tutorial we've learned how to upload files from our Ionic app to Firebase Storage. Besides, as an additional feature we learned how to crop the selected image.
If you want to learn more about image handling in Ionic appa, check out the following guide Image Picker and Image Cropper in Ionic Framework.
Also, if you want to learn how to save the data submitted on a form into a Firestore database, check out the tutorial Ionic Firebase Database.
If you wish to keep learning about Firebase and Ionic, we have been writing about Firebase Authentication and also published a complete Firebase CRUD tutorial.
I hope this tutorial was helpful for you. If you have any questions don’t hesitate to leave a comment on the section below.
Also, you can check out our detailed and professional Ionic Starter App crafted with love and dedication to help you create better apps and supercharge your productivity.
Liked this Ionic Tutorial?
Leave your comments below.