How to upload multiple files to Firebase?

前端 未结 8 1886
既然无缘
既然无缘 2020-12-04 16:44

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

fileButton.addEventListener(\'chang         


        
8条回答
  •  不知归路
    2020-12-04 17:50

    all the promises get messy pretty quickly, why not use async and await instead?

    Here, I have a function that keep tracks of all the images selected from the input/file control to be uploaded:

    let images =[];
    let imagePaths=[];
    
    const trackFiles =(e)=>{
        images =[];
        imagePaths =[];
        for (var i = 0; i < e.target.files.length; i++) {
            images.push(e.target.files[i]);
        }
    }
    

    And I have another function that will be triggered by a button that the user will click on when ready to do the actual upload:

    const uploadFiles =()=>{
        const storageRef = storage.ref();
    
        images.map(async img =>{
            let fileRef = storageRef.child(img.name);
            await fileRef.put(img);
            const singleImgPath = await fileRef.getDownloadURL();
            imagePaths.push(singleImgPath);
    
            if(imagePaths.length == images.length){
                console.log("got all paths here now: ", imagePaths);
            }
        })
    }
    

    We basically loop through each image and perform the upload, and push the image paths into a separate imagePaths array one by one as each of them gets finished at its own pace, I then grab all the paths once we know they are all done by comparing the length of the images and their final paths.

提交回复
热议问题