HTTP POST and Google Apps Script file upload

2020-07-22 19:33发布

问题:

Forgive the possible duplicity of this question, but after hours of searching to no avail, I've elected to ask the following of the community:

Is there any means by which, using the following form with HTML and Javascript (with a POST or GET request) that I might be able to have a user, from a normal HTML page, be able to submit and upload a file to Google Drive by means of having the "form action =" being directed at a Google Script?

I have been able to successfully write values to a Google Spreadsheet using only a form action directed to a Google Script which holds a single doPost(e) which then grabs the e.parameter.[input_field_name_here] and performs the calculations.

I have been toying with a combination of methods, but this is about as far as I've been able to get.

Current HTML:

<form method="post" action="my_google_script_published_as_web_app_url/exec" name="quoteForm" id="quoteForm" target="hidden_iframe"> 
  <input type="file" name = "thefile">
</form> 

Google Apps Script

function doPost(e) 
   {
   var fileBlob = e.parameter.thefile;
   Logger.log(e);
   Logger.log(fileBlob);
   var doc = DocsList.createFile(fileBlob.getBlob());
   }

I have attempted the following variations with the code in order to try to perform an upload via this method:

  • Added the enctype="multipart/form-data" to the form to see if that was an issue.
  • Attempted to use a "GET" request instead.

The closest I have been able to get in terms of an acutal useable result is an error return of "unable to convert Array to BlobSource" and, a further result of "unable to to call .getBlob() on type string" as well as "...on type Object".

Is there any hope to this at all? I've been trying to glean what I could from here, as well as the following two issues regarding what sounds like bugs related to a method like this here and here with the latter seeming the closest to what I'm facing.

Many thanks in advance for any assistance on this matter.

回答1:

I think this is still 'broken'. Whether it is intended to remain so, I don't know. After some exhaustive trial and error, I concluded that although it is possible to get a doPost to execute, you are never going to get a usable response (and I can't think of a case where you would not care whether the upload is successful or not). Basically you come up against the cross-domain issue which is solved for you in the htmlService example. 'get' will never work for the upload.



回答2:

Due to the changes in the recent years, you can specify the contentType and save it to your cloud using DriveApp:

  var contentType = 'image/jpeg';
  var img = e.imageFile;
  var img = img.getAs(contentType);
  var destination = DriveApp.getFolderById(destination_id);
  destination.createFile(img);

Also make sure that your html is working correctly. You haven't specified any submit input.