0
votes

I have a React form where the user can upload multiple files. These are stored in fileList

async function uploadFiles(id) {
    try {
        const meta = await storageUploadFile(fileList, id);
        console.log(meta);
    } catch (e) {
        console.log(e);
    }
}

This calls my helper function that uploads the files to Firebase

export const storageUploadFile = function(files, id) {
    const user = firebase.auth().currentUser.uid;
    return Promise.all(
        files.map((file) => {
            return storage.child(`designs/${user}/${id}/${file.name}`).put(file)
        })
    )
};

What I'd like is on calling uploadFiles, get the total filesize of all items, and then show the overall progress.

At the moment, my code is only returning the file status in an array on completion

[
 {bytesTransferred: 485561, totalBytes: 485561, state: "success"},
 {bytesTransferred: 656289, totalBytes: 656289, state: "success"}
]
1

1 Answers

0
votes

This is the way i do it:

import Deferred from 'es6-deferred';

export const storageUploadFile = function(files, id) {
  const user = firebase.auth().currentUser.uid;
  // To track the remaining files
  let itemsCount = files.length;
  // To store our files refs
  const thumbRef = [];
  // Our main tasks
  const tumbUploadTask = [];
  // This will store our primses
  const thumbCompleter = [];
  for (let i = 0; i < files.length; i += 1) {
    thumbRef[i] = storage.ref(`designs/${user}/${id}/${file.name}`);
    tumbUploadTask[i] = thumbRef[i].put(files[i]);
    thumbCompleter[i] = new Deferred();
    tumbUploadTask[i].on('state_changed',
      (snap) => {
        // Here you can check the progress
        console.log(i, (snap.bytesTransferred / snap.totalBytes) * 100);
      },
      (error) => {
        thumbCompleter[i].reject(error);
      }, () => {
        const url = tumbUploadTask[i].snapshot.metadata.downloadURLs[0];
        itemsCount -= 1;
        console.log(`Items left: ${itemsCount}`)
        thumbCompleter[i].resolve(url);
      });
  }
  return Promise.all(thumbCompleter).then((urls) => {
    // Here we can see our files urls
    console.log(urls);
  });
};

Hope it helps.