Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created February 17, 2020 23:42
Show Gist options
  • Save tanaikech/280b782ee0518aa083a4fe0d71384823 to your computer and use it in GitHub Desktop.
Save tanaikech/280b782ee0518aa083a4fe0d71384823 to your computer and use it in GitHub Desktop.
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();

@draxdeveloper
Copy link

Hello!

It's possible to return the obj instead of using a google.script.run?

Here is my issue:

I need to get the values of a series of inputs, including two inputs that are of the type input file.
Then I need to send all those values as params to a google.script.run function.

In other words, before send the object to the server side, I need to capture other values, including two files.

@saymonleite
Copy link

@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();

Friend, where specifically do I put this line of code?

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