Handling multiple files from an input element in an array with Google Apps Script

As of right now you have to use a work around to work with multiple files. The multiple attribute only works in IFRAME mode, but file inputs are broken in IFRAME mode.

To see this workaround take a look at the bug submission for this issue:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=4610

Also in your code you have some mixing of server side and client side code that will not work:

var folder = DriveApp.getFolderById(dropBoxId); //server side
var input = document.getElementById('myFiles'); //client side

You will need to do your multiple file processing on the client side

I came up with a nice solution for multi-file uploading. Limitations are files must be under 10 MB.

CODE.GS

function doGet() {
 return HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);

}

function saveFile(data,name,folderId) {

var contentType = data.substring(5,data.indexOf(';'));
var file = Utilities.newBlob(Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)), contentType, name);
  DriveApp.getFolderById(folderId).createFile(file);

}

index.html

<div>
 <input type="file"  id="myFiles" name="myFiles" multiple/>
 <input type="button" value="Submit" onclick="SaveFiles()" />
</div>

<script>

  var reader = new FileReader();
  var files;
  var fileCounter = 0;
  var folderId = "";




  reader.onloadend = function () {
   google.script.run
    .withSuccessHandler(function(){
      fileCounter++;      
      postNextFile();
    }).saveFile(reader.result,files[fileCounter].name,folderId);

  }



function SaveFiles(){
  var folderSelect = document.getElementById("folderSelectId");
  folderId = folderSelect.options[e.selectedIndex].value;
  files = document.getElementById("myFiles").files;  
  postNextFile();
 }


function postNextFile(){if(fileCounter < files.length){reader.readAsDataURL(files[fileCounter]);}else{fileCounter=0;alert("upload done")}}

</script>

Leave a Comment