Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created February 17, 2020 23:42
Embed
What would you like to do?
Uploading File to Google Drive using HTML and Google Apps Script

Uploading File to Google Drive using HTML and Google Apps Script

This is a simple sample script for uploading a file using the file input tag of HTML. As the important point, the file is sent as the byte array for using Google Apps Script. By this, at Google Apps Script side, the byte array can be converted to a blob using a simple script.

HTML & Javascript

<input id="file" type="file" onchange="saveFile(this)" />
<script>
  function saveFile(f) {
    const file = f.files[0];
    const fr = new FileReader();
    fr.onload = function(e) {
      const obj = {
        filename: file.name,
        mimeType: file.type,
        bytes: [...new Int8Array(e.target.result)]
      };
      google.script.run.withSuccessHandler(e => console.log(e)).saveFile(obj);
    };
    fr.readAsArrayBuffer(file);
  }
</script>

Google Apps Script

function saveFile(e) {
  var blob = Utilities.newBlob(e.bytes, e.mimeType, e.filename);
  DriveApp.createFile(blob);
  return "Done.";
}
@obaez004
Copy link

Thank you!
How can I return the FileUrl to use in a inputbox in the html file?

@AdrianoSilva1985
Copy link

Awesome, man. Thank you so much. I trying to find a code like this for a long time. I'm very grateful.

@Richard7w7
Copy link

i love you men <3 <3

@GenjiHatakata
Copy link

GenjiHatakata commented May 18, 2022

@obaez004

Thank you! How can I return the FileUrl to use in a inputbox in the html file?

var file = DriveApp.createFile(blob);
return file.getUrl();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment