Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Uploading Local Files to Google Drive without Authorization using HTML Form

Uploading Local Files to Google Drive without Authorization using HTML Form

This is a sample script for uploading local file to Google Drive without the authorization using HTML form. A selected file in your local PC using HTML form is uploaded to Google Drive and saved to Google Drive.

When you use this, at first, please deploy Web Apps. The script is doPost() of following scripts.

Script : Google Apps Script

function doPost(e) {
  var data = Utilities.base64Decode(e.parameters.data);
  var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.filename);
  DriveApp.createFile(blob);
  var output = HtmlService.createHtmlOutput("<b>Done!</b>");
  output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  return output;
  // return ContentService.createTextOutput("Done.") <--- Here, an error occurred.
}

Flow :

  • Retrieve data, filename and mimetype as e.parameters.data, e.parameters.filename and e.parameters.mimetype, respectively.
  • Decode the data using Utilities.base64Decode().
  • Create blob using Utilities.newBlob().
  • Create the file in the root folder of Google Drive.

Script : HTML

https://script.google.com/macros/s/#####/exec is the URL obtained when the Web Apps was deployed. Please replace it to your Web Apps URL. You can open this HTML for the browser of your local PC.

<!DOCTYPE html>
<html>

<head>
    <title>Sample script for uploading file to Google Drive without authorization</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
</head>

<body>
    <form action="https://script.google.com/macros/s/#####/exec" id="form" method="post">
        Upload a file
        <div id="data"></div>
        <input name="file" id="uploadfile" type="file">
        <input id="submit" type="submit">
    </form>
    <script>
    $('#uploadfile').on("change", function() {
        var file = this.files[0];
        var fr = new FileReader();
        fr.fileName = file.name;
        fr.onload = function(e) {
            e.target.result
            html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
            html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
            html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
            $("#data").empty().append(html);
        }
        fr.readAsDataURL(file);
    });
    </script>
</body>

</html>

Flow :

  • Using FileReader(), retrieve base64 encoded file, filename and mimetype.
  • Add input with type="hidden" to #form as text data.
    • replace(/^.*,/, '') is used for removing a header of encoded data.
    • match(/^.*(?=;)/)[0] is used for retrieving mimetype of uploading file.
  • When a submit button is clicked, the base64 data is sent to doPost() of GAS.

Note :

  • In order to use this, after the script is modified, please redeploy Web Apps as a new version. By this, the latest script is reflected to Web Apps.
  • This sample script can upload one file. If you want to upload several files, please modify script. var file = this.files[0]; means the selected first file. When there are some files, it is files[1], files[2] .....

Reference :

  • For downloading files on Google Drive to local PC, I have already published here.

Updated:

@Ansoriarts

This comment has been minimized.

Copy link

@Ansoriarts Ansoriarts commented Sep 10, 2018

I want to create an html form that will input data (e-mail, name, and message, for example) and image file (minimum .jpg / .jpeg) to Google Spreadsheet in the form of data and incoming file links, as well as inserting image files into the google drive folder. Then the data and the file link also go to my email contact.

The most important value for me is, after the user presses the submit button, in the onload process, the user is not directed to the Google Apps Script link, but the user is treated with a message of thanks or greeting that the data and files inputted are actually sent to the Google Spreadsheet, Drive database , and of course my Gmail.

How do I make a script and html on a site?

@ifelipeg

This comment has been minimized.

Copy link

@ifelipeg ifelipeg commented Dec 5, 2018

THANK YOU VERY MUCH!!!! I LOVE YOU jajaj

@datepickerUser

This comment has been minimized.

Copy link

@datepickerUser datepickerUser commented Jan 4, 2019

Hi,Thanks for this script.
The script after it has run opens a new page and shows"Done". I am using this in a static html page on my computer to upload files- so I want this "Done" to go into a <div id="response" ...how to get this response into the div...thanks for your help

@ctosid

This comment has been minimized.

Copy link

@ctosid ctosid commented Feb 6, 2019

I didn't get "Done" msg though image got saved, any idea, but anyways thanks alot. Good Work.
image

@urwa

This comment has been minimized.

Copy link

@urwa urwa commented Apr 5, 2019

life saver!

@e-labInnovations

This comment has been minimized.

Copy link

@e-labInnovations e-labInnovations commented Apr 7, 2019

After uploading file it opens the script file text. How can I show script message in that same page on a

tag?

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Apr 7, 2019

  1. If you want to retrieve the selected file on Javascript, please modify Javascript.
  2. If you want to retrieve the uploaded file on Google Drive, please modify the Google Apps Script.
@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Apr 7, 2019

I couldn't replicate the situation that "Done" is not displayed. Can you provide the detail flow for replicating your situation?

@prt0100

This comment has been minimized.

Copy link

@prt0100 prt0100 commented Jun 26, 2019

Thank you!

@Max-Makhrov

This comment has been minimized.

Copy link

@Max-Makhrov Max-Makhrov commented Oct 21, 2019

Hi Tanaikech!

Great work, thank you!
I've used the code in my project and met the same error:

script.google...com refused to connect.

The error occurred when I used the code from the Google Sheets Script project.

I've solved it with this code:

  var output = HtmlService.createHtmlOutput("<b>Done!</b>");
  output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  return output;

Please see if it helps with your work, here's my fork.

Have a nice day and thank you again!

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Oct 21, 2019

@Max-Makhrov Thank you so much for your support. By your comment, the error could be removed. I couldn't notice about it. I think that your modification is useful for other users. Thank you so much again.

@ddevey

This comment has been minimized.

Copy link

@ddevey ddevey commented Nov 6, 2019

Can anyone help? I constantly get the message "Script function not found: doGet" even though I am republishing as a new script every time.

@christales

This comment has been minimized.

Copy link

@christales christales commented Nov 12, 2019

Can anyone help? I constantly get the message "Script function not found: doGet" even though I am republishing as a new script every time.

@ddevey Google webApp/sites require a simple doGet function in the script. Let's say you named your html file 'upload.html' within the project, where you pasted tanaikech's html code. (remember to replace the published ID in line 10 of the html after publishing!)

function doGet() {
  return HtmlService.createHtmlOutputFromFile('upload');
}

@tanaikech care to add it to your instructions?

fork

@Max-Makhrov

This comment has been minimized.

Copy link

@Max-Makhrov Max-Makhrov commented Nov 13, 2019

Can anyone help? I constantly get the message "Script function not found: doGet" even though I am republishing as a new script every time.

Adding an empty doGet works:

function doGet(e) {
}
@christales

This comment has been minimized.

Copy link

@christales christales commented Nov 13, 2019

@christales

This comment has been minimized.

Copy link

@christales christales commented Nov 17, 2019

Can anyone help? I constantly get the message "Script function not found: doGet" even though I am republishing as a new script every time.

Adding an empty doGet works:

function doGet(e) {
}

Just checked the empty doGet(e) and for some reason it returns 'The script completed but did not return anything'. Coming back to return htmlservice works.

@dmsac

This comment has been minimized.

Copy link

@dmsac dmsac commented Dec 19, 2019

Thank you! But we always want more, right?
Is there an option for specifying a folder, rather than uploading to the root MyDrive in Google?

Thanks so much.

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Dec 20, 2019

@dmsac How about this? DriveApp.getFolderById(id).createFile(blob); instead of DriveApp.createFile(blob); Ref

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Dec 20, 2019

@Max-Makhrov Thank you so much for your support.

@dmsac

This comment has been minimized.

Copy link

@dmsac dmsac commented Dec 20, 2019

Yes! getFolderByID(id) worked marvelously!

Thank you!

@dmsac

This comment has been minimized.

Copy link

@dmsac dmsac commented Dec 20, 2019

@tanaikech -- any thoughts about having the page automatically reload, so that multiple files can be uploaded? I can add instructions (with the Done! message) to refresh the page in the browser to upload another file--but it would be nice if the upload interface just refreshed automatically.

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Dec 20, 2019

@dmsac

This comment has been minimized.

Copy link

@dmsac dmsac commented Dec 21, 2019

Looks very interesting. Need to look at it more to understand constraints it may assume. In our case, we just have users uploading multiple files from their PCs to a Google Drive folder that we designate. Your single file app works well; I'm just seeking to make it easy to also upload more than one file --either serially or, as in this new app, all in a single upload. We're not dealing with lots of large files at this point, although that could be needed on occasion.

@vathzen

This comment has been minimized.

Copy link

@vathzen vathzen commented Dec 26, 2019

Im Getting this error when i upload files:

Could not decode string. (line 2, file "Code", project "PROJECT_NAME")

Whats the cause and how do i solve this?

EDIT: I'm Hosting a website elsewhere (Not on Google App SCripts) and trying to upload files to my Drive

@Kishoreramesh07

This comment has been minimized.

@daahanov

This comment has been minimized.

Copy link

@daahanov daahanov commented Mar 4, 2020

Is this useful for your situation? https://github.com/tanaikech/AsynchronousResumableUploadForGoogleDrive

beautuful solution, just love this sidebar thing, bun I'm not an experienced sript editor and could not manage to change destination folder, files are uploaded only in root of MyDrive folder.
every time I activate this

function getAuth() {
  // DriveApp.createFile(blob) // This is used for adding the scope of "https://www.googleapis.com/auth/drive".
  return ScriptApp.getOAuthToken();
}

upload just stop working, same for DriveApp.getFolderById(id).createFile(blob)

@christales

This comment has been minimized.

Copy link

@christales christales commented Mar 4, 2020

Is this useful for your situation? https://github.com/tanaikech/AsynchronousResumableUploadForGoogleDrive

beautuful solution, just love this sidebar thing, bun I'm not an experienced sript editor and could not manage to change destination folder, files are uploaded only in root of MyDrive folder.
every time I activate this

function getAuth() {
  // DriveApp.createFile(blob) // This is used for adding the scope of "https://www.googleapis.com/auth/drive".
  return ScriptApp.getOAuthToken();
}

upload just stop working, same for DriveApp.getFolderById(id).createFile(blob)

are you getting any permission related errors when running the script from the editor?
I had to update my manifest file with "https://www.googleapis.com/auth/script.external_request" after switching to V8
Not sure if it's related though

@daahanov

This comment has been minimized.

Copy link

@daahanov daahanov commented Mar 4, 2020

are you getting any permission related errors when running the script from the editor?
I had to update my manifest file with "https://www.googleapis.com/auth/script.external_request" after switching to V8

No, do not get any errors, the script runs, sidebar is created, I can choose files, but nothing happening after I click 'upload' button.
Tried both runtime versions.

@christales

This comment has been minimized.

Copy link

@christales christales commented Mar 4, 2020

are you getting any permission related errors when running the script from the editor?
I had to update my manifest file with "https://www.googleapis.com/auth/script.external_request" after switching to V8

No, do not get any errors, the script runs, sidebar is created, I can choose files, but nothing happening after I click 'upload' button.
Tried both runtime versions.

Perhaps getting a console.log of every step could help with pinpointing where the issue is, after tracing the steps in stackdriver

@daahanov

This comment has been minimized.

Copy link

@daahanov daahanov commented Mar 5, 2020

@christales

Perhaps getting a console.log of every step could help with pinpointing where the issue is, after tracing the steps in stackdriver

Thank You, that helped. I get Reference Error Object 'blob' undefined (it's on russian for me so text may not be exactly the same as original). By this I now understand that I supposed to join these two scripts by @tanaikech somehow but don't know how, still need to figure this out.

@christales

This comment has been minimized.

Copy link

@christales christales commented Mar 5, 2020

@christales

Perhaps getting a console.log of every step could help with pinpointing where the issue is, after tracing the steps in stackdriver

Thank You, that helped. I get Reference Error Object 'blob' undefined (it's on russian for me so text may not be exactly the same as original). By this I now understand that I supposed to join these two scripts by @tanaikech somehow but don't know how, still need to figure this out.

I'm afraid resumably uploading multiple files asynchronously won't work without authorization. Note that the current script uses a script macro, whereas async upload requires "https://www.googleapis.com/upload/drive/" authorization to be able to choose uploadType=resumable as written in ResumableUploadForGoogleDrive_js library.

The easiest solution would be to stick to the marvelous original script @tanaikech created and require each user to authorize.
Someone more knowledgeable would have to comment on this, perhaps @tanaikech would have a moment ;)

@nazariodili

This comment has been minimized.

Copy link

@nazariodili nazariodili commented Mar 6, 2020

Thank u so much!
Is there a way to receive an email with the new file uploaded as attachment?

@pankajjossy1

This comment has been minimized.

Copy link

@pankajjossy1 pankajjossy1 commented Jun 13, 2020

i am not very much into tech pls make a youtube video on this

@natexecuit

This comment has been minimized.

Copy link

@natexecuit natexecuit commented Jul 9, 2020

Getting the following error after copying and pasting the code:
Exception: Unexpected error while getting the method or property newBlob on object Utilities. (line 3, file "Code")

@coldes

This comment has been minimized.

Copy link

@coldes coldes commented Jul 26, 2020

...anyone? after submit how to prevent GAScript from loading in a new browser window - ie just have "Done" display in index.html

@niteshkumar2000

This comment has been minimized.

Copy link

@niteshkumar2000 niteshkumar2000 commented Aug 9, 2020

Hello I need small help my form already has one existing action link(which is google form), Is there any way to do this on upload itself instead of submit?

@robertod10

This comment has been minimized.

Copy link

@robertod10 robertod10 commented Sep 18, 2020

When I run your codes and i get this error in appscript:

TypeError: Cannot read property 'parameters' of undefined (línea 2, archivo "Código")

I need help please (english or spanish)

@Kishoreramesh07

This comment has been minimized.

Copy link

@Kishoreramesh07 Kishoreramesh07 commented Sep 23, 2020

How to validate particular file type in GAS for example only PDF

@Thinnakorn16

This comment has been minimized.

Copy link

@Thinnakorn16 Thinnakorn16 commented Oct 4, 2020

I want to select which folder to store the images, how should I adjust the code?

@MrN8b

This comment has been minimized.

Copy link

@MrN8b MrN8b commented Feb 3, 2021

Thanks for the script. This has gotten me farther in uploading files from guests than anything else so far. I do have three questions and im new at this so please try to explain in detail how to do it.

  1. I need to be able to create a folder of the submitter's name for all of the uploads they send in. How do I get it to create a folder inside of google drive based on a form field?
  2. I saw the comment you made about multiple file uploads but because im new to this I didnt follow what you were trying to say. I would like for the users to be able to upload 10 files at once to my google drive.
  3. This has to do with the first question a bit. If I just wanted all of the submitted files to go into a folder on my Drive how do I set that up instead of being dumped into the root folder?

Thanks

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