Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload multiple files to Firebase?

Is there a way to upload multiple files to Firebase storage. It can upload single file within single attempt as follows.

fileButton.addEventListener('change', function(e){ 
//Get file
var file = e.target.files[0];

//Create storage reference
var storageRef = firebase.storage().ref(DirectryPath+"/"+file.name);

//Upload file
var task = storageRef.put(file);

//Update progress bar
  task.on('state_changed',
    function progress(snapshot){

        var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100;
        uploader.value = percentage;
    },
    function error(err){

    },
    function complete(){
        var downloadURL = task.snapshot.downloadURL;

    }
  );

});

How to upload multiple files to the Firebase storage.

like image 438
isuru Avatar asked Jan 16 '17 09:01

isuru


People also ask

How do I upload documents to Firebase?

Upload from a Blob or File Once you've created an appropriate reference, you then call the uploadBytes() method. uploadBytes() takes files via the JavaScript File and Blob APIs and uploads them to Cloud Storage.

How do I upload folders to Firebase storage?

There is no way to upload an entire folder to Cloud Storage for Firebase in one go. You will have to upload the individual files in the folder. The is no concept of an empty folder in Cloud Storage for Firebase. Folders only exist by the fact that they have files in them.

How to send multiple files to firebase at the same time?

Build a dropzone file uploader in Angular that can send multiple files to Firebase storage simultaneously. 1050 words. Firebase makes it easy to upload a huge payload of raw files a cloud storage bucket.

How do I upload files to Firebase Storage with angular?

The following lesson will teach you how to upload files to Firebase Storage with Angular, including several advanced concepts about how to… Handle multiple simultaneous concurrent file uploads. Save the resulting download URL to Firestore. Display a progress bar and provide UI controls to pause, cancel, and resume uploads.

What is Firebase Cloud storage for Firebase?

Cloud Storage for Firebase allows you to quickly and easily upload files to a Cloud Storage bucket provided and managed by Firebase. Note: By default, a Cloud Storage bucket requires Firebase Authentication to perform any action on the bucket's data or files.

How do I add firebase to a project in Visual Studio?

If you didn’t add the Firebase Storage permission manually in the build.gradle file, you can use the Tools menu and select Firebase. This will pop out the Firebase Assistant with a list of menu choices. Scroll down to Storage and add Firebase to your project. Choose an existing project or create a new one then add Firebase Storage dependency.


4 Answers

I found the solution for my above question and I like to put it here because it can be useful for anyone.

//Listen for file selection
fileButton.addEventListener('change', function(e){ 
    //Get files
    for (var i = 0; i < e.target.files.length; i++) {
        var imageFile = e.target.files[i];

        uploadImageAsPromise(imageFile);
    }
});

//Handle waiting to upload each file using promise
function uploadImageAsPromise (imageFile) {
    return new Promise(function (resolve, reject) {
        var storageRef = firebase.storage().ref(fullDirectory+"/"+imageFile.name);

        //Upload file
        var task = storageRef.put(imageFile);

        //Update progress bar
        task.on('state_changed',
            function progress(snapshot){
                var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100;
                uploader.value = percentage;
            },
            function error(err){

            },
            function complete(){
                var downloadURL = task.snapshot.downloadURL;
            }
        );
    });
}
like image 80
isuru Avatar answered Oct 19 '22 15:10

isuru


Firebase Storage uses Promise, so you can use Promises to achieve it.

Here's the firebase blog article that covers this subject: Keeping our Promises (and Callbacks)


Give Promise.all() an "Array of Promises"

Promise.all(
  // Array of "Promises"
  myItems.map(item => putStorageItem(item))
)
.then((url) => {
  console.log(`All success`)
})
.catch((error) => {
  console.log(`Some failed: `, error.message)
});

Upload each file and return a Promise

putStorageItem(item) {
  // the return value will be a Promise
  return firebase.storage().ref("YourPath").put("YourFile")
  .then((snapshot) => {
    console.log('One success:', item)
  }).catch((error) => {
    console.log('One failed:', item, error.message)
  });
}

YourPath and YourFile can be carried with myItems array (thus the item object).

I omitted them here just for readability, but you get the concept.

like image 45
user2875289 Avatar answered Oct 19 '22 17:10

user2875289


I believe there's a simpler solution:

// set it up
firebase.storage().ref().constructor.prototype.putFiles = function(files) { 
  var ref = this;
  return Promise.all(files.map(function(file) {
    return ref.child(file.name).put(file);
  }));
}

// use it!
firebase.storage().ref().putFiles(files).then(function(metadatas) {
  // Get an array of file metadata
}).catch(function(error) {
  // If any task fails, handle this
});
like image 13
Mike McDonald Avatar answered Oct 19 '22 16:10

Mike McDonald


        let ad_images=["file:///data/user/0/..../IMG-20181216-WA00001.jpg",
                       "file:///data/user/0/..../IMG-20181216-WA00002.jpg",
                       "file:///data/user/0/..../IMG-20181216-WA00003.jpg"];
        let firebase_images=[];

        const ref = firebase.firestore().collection('ads').doc(newRecord.id);
        putStorageItem = (url,index,ext) => {
            return firebase.storage().ref('YOURFOLDER/'+ index +'.'+ext ).putFile(url)
            .then((snapshot) => {
                console.log(snapshot)
                firebase_images[index] = snapshot.downloadURL;              
                //OR
                //firebase_images.push(snapshot.downloadURL);
            }).catch((error) => {
                console.log('One failed:', error.message)
            });
        }

        Promise.all(
            ad_images.map( async (item,index) => {
                let ext = item.split('/').pop().split(".").pop();
                console.log(newRecord.id, item, index, ext);
                await putStorageItem(newRecord.id, item, index, ext);
            })
        )
        .then((url) => {
            console.log(`All success`);
            console.log(firebase_images);
        })
          .catch((error) => {
            console.log(`Some failed: `, error.message)
        });
like image 3
Akın Köker Avatar answered Oct 19 '22 17:10

Akın Köker