Skip to content

Latest commit

 

History

History
76 lines (53 loc) · 1.88 KB

6. Firebase Storage.md

File metadata and controls

76 lines (53 loc) · 1.88 KB

Firebase Storage

Cloud Storage for Firebase lets you upload and share user generated content, such as images and video, which allows you to build rich media content into your apps.

File Storage Operation

<input type="file" onchange="uploadFile()" id="files" name="files[]" multiple />
  
<script>
//function to save file
    function uploadFile(){
      var storage = firebase.storage();

      var file = document.getElementById("files").files[0];
        console.log(file);
      
      var storageRef = firebase.storage().ref();
      
      //dynamically set reference to the file name
      var thisRef = storageRef.child(file.name);

      //put request upload file to firebase storage
      thisRef.put(file).then(function(snapshot) {
        console.log('Uploaded a blob or file!');
      });
    }

  </script>

Get Download URL

To Get the specific file download URL, you need to call getDownloadURL()

    firebase.storage().ref('img').child('FILENAME.PNG').getDownloadURL().then(url=>console.log(url))
    }).catch(e=>console.log(e))
    

Remove/Delete File

To delete the specific file, you need to call delete()

    function deleteFile(filename){
      firebase.storage().ref('img').child(filename).delete().then(()=>{
          console.log('File Removed')
      }).catch(e=>console.log(e))
    }
    

Read all the files

To get all the files you need to call listAll()

    function getAllFiles(){
      firebase.storage().ref('img').listAll().then(files=>{
          console.log(files.items)
          files.items.forEach(file=>{
              getImageURL(file)
          })
      })
    }
    
    function getImageURL(imgRef){
      imgRef.getDownloadURL().then(url=>{
          console.log(url)
      }).catch(e=>console.log(e))
    }