Google Apps Script to Upload Multiple Files From Local Storage to Google Drive Using HTML5 Forms in Browser Using Javascript Full Project For Beginners

 

 

Google Apps Script: Code.gs

 

 

function saveFile(obj) {
  var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName);
  return DriveApp.createFile(blob).getId();
}

 

 

HTML: Index.html

 

 

<input name="file" id="files" type="file" multiple>
<input type='button' value='Upload' onclick='getFiles()'>

<script>
function getFiles() {
  const f = document.getElementById('files');
  [...f.files].forEach((file, i) => {
    const fr = new FileReader();
    fr.onload = (e) => {
      const data = e.target.result.split(",");
      const obj = {fileName: f.files[i].name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]};
      google.script.run.withSuccessHandler((id) => {
        console.log(id);
      }).saveFile(obj);
    }
    fr.readAsDataURL(file);
  });
}
</script>

 

 

Google Apps Script: Code:gs

 

 

function createZip(obj) {
    var blobs = obj.map(function(e) {
        return Utilities.newBlob(Utilities.base64Decode(e.data), e.mimeType, e.fileName);
    });
    var zip = Utilities.zip(blobs, "filename.zip");
    return DriveApp.createFile(zip).getId();
}

 

 

HTML: Index.html

 

 

<input name="file" id="files" type="file" multiple>
<input type='button' value='Upload' onclick='getFiles()'>

<script>
function getFiles() {
  const f = document.getElementById('files');
  const r = Promise.all([...f.files].map((file, i) => {
    const fr = new FileReader();
    return new Promise((r) => {
      fr.onload = (e) => {
        const data = e.target.result.split(",");
        return r({fileName: f.files[i].name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]});
      }
      fr.readAsDataURL(file);
    });
  }))
  .then((obj) => {
    google.script.run.withSuccessHandler((id) => {
      console.log(id);
    }).createZip(obj);
  });
}
</script>

Leave a Reply