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 {
      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 {
      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 =;
    // Create a storage reference from storage service
    var storageRef = storage.ref();

    or you can do it by joining both together

    var storageRef =;

    you can use another non-default bucket storage:

    // Get a non-default Storage bucket
    var 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=""></script>
    // Initialize Firebase
      var config = {
        apiKey: "XXXXXXXXXXXXX",
        authDomain: "XXXXXXXXXXXXX",
        databaseURL: "XXXXXXXXXXXXX",
        projectId: "XXXXXXXXXXXXX",
        storageBucket: "XXXXXXXXXXXXX",
        messagingSenderId: "XXXXXXXXXXXXX"
    <div id="filesubmit">
      <input type="file" class="file-select" accept="image/*"/>
      <button class="file-submit">SUBMIT</button>
    <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 =[0];
    function handleFileUploadSubmit(e) {
       // Get a reference to the storage service, which is used to create references in your storage bucket
       var storage =;
       // Create a storage reference from our storage service
       var storageRef = storage.ref();
       const uploadTask = storageRef.child(`${}`).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(, // 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 // or 'paused'
    	        console.log('Upload is paused');
    	      case // or 'running'
    	        console.log('Upload is running');
         }, function(error) {
            // A full list of error codes is available at
            switch (error.code) {
                case 'storage/unauthorized':
                      // User doesn't have permission to access the object
                case 'storage/canceled':
                     // User canceled the upload
                case 'storage/unknown':
                     // Unknown error occurred, inspect error.serverResponse
         }, function() {
            // Upload completed successfully, now we can get the download URL
            uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
              console.log('File available at', downloadURL);

    Hope it helps.

Leave a Reply

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

Back to Top