Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Firebase Storage Using AngularJS

DZone's Guide to

Firebase Storage Using AngularJS

Firebase allows you to securely upload and download files for Firebase apps, as well as store images, audio, and videos.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

Recently, we got an awesome post about Firebase and how to use the real-time database with AngularJS. If you missed it here you go the link. Today, I want to talk about another useful feature of Firebase: an amazing tool that allows us to store and serve user-generated content, such as photos or videos. As they explained on their website:

Firebase Storage adds Google security to file uploads and downloads for your Firebase apps, regardless of network quality. You can use it to store images, audio, video, or other user-generated content.

Adding Firebase to Your Web App

If you read my previous post, you already know how to add Firebase reference to your website. If you didn't it yet, go and read it first here.

Creating Your Data Layer

As I did for the real-time database, I'm going to create a data layer. To do that, I'm going to create an AngularJS service to use as a data layer. This service will be responsible to create our links to the Firebase store. As you can see below, it is quite similar to the one we use to connect to our real-time database.

 function storageService($http, $firebaseArray, $firebaseObject, $q) {
    var root = firebase.database().ref();
    var storageRef = firebase.storage().ref();
 }

Now, we have the reference so that we can add a function to our service in order to upload the image.

 function upload(file, uid, fileName) {
    var deferred = $q.defer();
    var fileRef = storageRef.child(uid).child(fileName);
    var uploadTask = fileRef.put(file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
       function(snapshot) {
          var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log('Upload is ' + progress + '% done');
          switch (snapshot.state) {
             case firebase.storage.TaskState.PAUSED:
               console.log('Upload is paused');
               break;
             case firebase.storage.TaskState.RUNNING:
               console.log('Upload is running');
               break;
          }
      },
      function(error) {
         switch (error.code) {
            case 'storage/unauthorized':
                deferred.reject('User does not have permission to access the object.');
                break;
            case 'storage/canceled':
                deferred.reject('User canceled the upload.');
                break;
            case 'storage/unknown':
                deferred.reject(' Unknown error occurred, Please try later.');
                break;
          }
       }, function() {
             deferred.resolve(uploadTask.snapshot.downloadURL);
       });

    return deferred.promise;
 }

Again, we use the function child to create the path. In my case, I'm using the user ID as a root folder so I'll group all files per user and then anotherchild  with the file name. At this point, it's important to highlight that I'm using the functionchild  twice but we can do it in this way child('folder_name/file_name') and will create the same structure.

Uploading the File

Once we get the reference, we need to use the put function to upload the file. This file object can be a blob, a file, or a byte array, and it returns a promise that allows us to trace the progress, catch errors, and handle the success response, which provides us a downloadURL property to get the public URL of our document. Our storage structure looks like this:

storage

As you can see, it's really easy to get this storage up and running. I have a working example at this link if you want to see the complete implementation. In this example, I created an app that allows you to select different places around the world and upload an image that appears in a google map.

For a complete reference of Firebase storage, use this link. For a complete reference of Angular Fire, use this link. For a complete reference of Firebase, use this link.

If you found this post useful, please don't forget to press the like button and share it. If you are in doubt, don't hesitate to ask a question. As always, thank you for reading.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
firebase ,storage ,mobile ,angularjs

Published at DZone with permission of Ezequiel Reyno. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}