FIrebase – upload files to cloud

Google Cloud Storage for Firebase lets you upload and share user generated content, such as images and video. Your data is stored in a Google Cloud Storage bucket, an exabyte scale object storage solution with high availability and global redundancy. Cloud Storage lets you securely upload these files directly from mobile devices and web browsers with resume and pause features. Here are some step to upload files in a web application to Google Cloud Storage:

  1. Add and configure SDK

    Before uploading files to storage, you have to add firebase SDK in your application. You can do this by following Add and configure the Firebase SDK

  2. Set up public access

    By default, only authenticated users can access storage to read or write data. Guest users can not upload data to storage. So you have to set up public access to storage. You can change storage rules from  Storage > Rules inside the Develop menu.

    As you can see, it only allow authenticated access to storage.

    service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {
          allow read, write: if request.auth != null;
        }
      }
    }

    comment or remove the rule as shown below and allow read, write access to all.

    service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {
          //allow read, write: if request.auth != null;
          allow read, write;
        }
      }
    }
  3. Create instance/reference to storage bucket

    In order to upload or download files, delete files, or get or update metadata, you must create a reference to the file you want to operate on. A reference can be thought of as a pointer to a file in the cloud. References are lightweight, so you can create as many as you need, and they are also reusable for multiple operations.In this tutorial we are using default storage bucket provided while creating project. You can create reference to storage bucket by following line of code:

    // Get a reference to the storage service, which is used to create references in your storage bucket
    var storage = firebase.storage();
    
    
    // Create a storage reference from storage service
    var storageRef = storage.ref();

    or you can do it by joining both together

    var storageRef = firebase.storage().ref();

    you can use another non-default bucket storage:

    // Get a non-default Storage bucket
    var storage = firebase.app().storage("gs://my-custom-bucket");

    for more detailed information, you can checkout official documentation: Firebase – create a reference

  4. Upload file to storage bucket

    Here is the complete code to upload a file. Replace firebase initialization config object with your initialization code snippet which you get in step 1.

    <script src="https://www.gstatic.com/firebasejs/5.4.2/firebase.js"></script>
    <script>
    // Initialize Firebase
      var config = {
        apiKey: "XXXXXXXXXXXXX",
        authDomain: "XXXXXXXXXXXXX",
        databaseURL: "XXXXXXXXXXXXX",
        projectId: "XXXXXXXXXXXXX",
        storageBucket: "XXXXXXXXXXXXX",
        messagingSenderId: "XXXXXXXXXXXXX"
      };
      firebase.initializeApp(config);
    </script>
    <div id="filesubmit">
      <input type="file" class="file-select" accept="image/*"/>
      <button class="file-submit">SUBMIT</button>
    </div>
    <script type="text/javascript">
    document.querySelector('.file-select').addEventListener('change', handleFileUploadChange.bind(this));
    document.querySelector('.file-submit').addEventListener('click', handleFileUploadSubmit.bind(this));
    let selectedFile;
    function handleFileUploadChange(e) {
       selectedFile = e.target.files[0];
    }
    
    function handleFileUploadSubmit(e) {
       // Get a reference to the storage service, which is used to create references in your storage bucket
       var storage = firebase.storage();
    
       // Create a storage reference from our storage service
       var storageRef = storage.ref();
    
       const uploadTask = storageRef.child(`${selectedFile.name}`).put(selectedFile); //create a child directory called images, and place the file inside this directory
       
       // Listen for state changes, errors, and completion of the upload.
       uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
         function(snapshot) {
    	    // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
    	    var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    	    console.log('Upload is ' + progress + '% done');
    	    switch (snapshot.state) {
    	      case firebase.storage.TaskState.PAUSED: // or 'paused'
    	        console.log('Upload is paused');
    	        break;
    	      case firebase.storage.TaskState.RUNNING: // or 'running'
    	        console.log('Upload is running');
    	        break;
    	    }
         }, function(error) {
            // A full list of error codes is available at
            // https://firebase.google.com/docs/storage/web/handle-errors
            switch (error.code) {
                case 'storage/unauthorized':
                      // User doesn't have permission to access the object
                      break;
                case 'storage/canceled':
                     // User canceled the upload
                     break;
                case 'storage/unknown':
                     // Unknown error occurred, inspect error.serverResponse
                     break;
              }
         }, function() {
            // Upload completed successfully, now we can get the download URL
            uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
              console.log('File available at', downloadURL);
            });
         });
    };
    </script>

    Hope it helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares