Uploading Multiple Files to Google Drive with Google App Script

后端 未结 5 704
萌比男神i
萌比男神i 2020-11-27 17:57

I\'m trying to upload multiple files at once with my app. It recognizes when there are 2 or more files being selected. However, it will only upload the 1st file that is sele

5条回答
  •  一生所求
    2020-11-27 18:29

    You have to send a file at a time trough the script.run, here's my implementation with FileReaders/ReadAsURL, which makes the file a Base64 string, which can be easily passed around:

    Notes:

    1. Dunno if it's necessary but I'm using IFRAME sandbox
    2. I left the progressBar in the code, you can remove it
    3. Everything must be OUTSIDE a form
    4. It accepts any file type

    HTML:

    // Upload de arquivo dentro das pastas Arquivos Auxiliares
    function iterarArquivosUpload() {
        var arquivos = document.getElementById('inputUpload').files;
    
        if (arquivos.length == 0) {
            alert('No file selected!');
        } else {
            //Show Progress Bar
            numUploads.total = arquivos.length;
            $('.progressUpload').progressbar({
                value : false
            });
            $('.labelProgressUpload').html('Preparando arquivos para upload');
    
            // Send each file at a time
            for (var arqs = 0; arqs < numUploads.total; arqs++) {
                console.log(arqs);
                enviarArquivoParaDrive(arquivos[arqs]);
            }
        }
    }
    
    function enviarArquivoParaDrive(arquivo) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var content = reader.result;
            console.log('Sending ' + arquivo.name);
            google.script.run.withSuccessHandler(updateProgressbar).uploadArquivoParaDrive(content, arquivo.name, currFolder);
        }
        reader.readAsDataURL(arquivo);
    }
    
    function updateProgressbar( idUpdate ){
       console.log('Received: ' + idUpdate);
       numUploads.done++;
       var porc = Math.ceil((numUploads.done / numUploads.total)*100);
       $('.progressUpload').progressbar({value: porc });
       $('.labelProgressUpload').html(numUploads.done +'/'+ numUploads.total);
       if( numUploads.done == numUploads.total ){
          uploadsFinished();
          numUploads.done = 0;
       };
    }
    

    Code.GS

    function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
      try{
        var splitBase = base64Data.split(','),
            type = splitBase[0].split(';')[0].replace('data:','');
    
        var byteCharacters = Utilities.base64Decode(splitBase[1]);
        var ss = Utilities.newBlob(byteCharacters, type);
        ss.setName(nomeArq);
    
        var file = DriveApp.getFolderById(idPasta).createFile(ss);
    
        return file.getName();
      }catch(e){
        return 'Erro: ' + e.toString();
      }
    }
    

提交回复
热议问题