Uploading file using Google Apps Script using Html

2019-01-11 16:01发布

问题:

How can I upload files to google drive? I want to create a web app using google app script - htmlservice. I don't know how to point form in html to existing google app script. I am having hard time to find a right example in google documentation.

I found hundreds of examples using UI but according to https://developers.google.com/apps-script/sunset it will be deprecated soon. Thank you in advance! Janusz

<html>
<body>
<form>
   <input type="file"/>
   <input type="button">
</form>
</body>
</html>

Script

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

function fileUploadTest()
{
   var fileBlob = e.parameter.upload;
      var adoc = DocsList.createFile(fileBlob);
      return adoc.getUrl();
}

回答1:

Have the button run the server side function using google.script.run, passing in the entire form as the only parameter. (Inside the button's onClick, 'this' is the button, so 'this.parentNode' is the form.) Make sure to give the file input a name.

<html>
<body>
<form>
   <input type="file" name="theFile">
   <input type="hidden" name="anExample">
   <input type="button" onclick="google.script.run.serverFunc(this.parentNode)">
</form>
</body>
</html>

On the server, have your form handling function take one parameter - the form itself. The HTML form from the client code will be transformed into an equivalent JavaScript object where all named fields are string properties, except for files which will be blobs.

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

function serverFunc(theForm) {
   var anExampleText = theForm.anExample;  // This is a string
   var fileBlob = theForm.theFile;         // This is a Blob.
   var adoc = DocsList.createFile(fileBlob);    
   return adoc.getUrl();
}

If you actually want to use that URL you are generating and returning, be sure to add a success handler to the google.script call. You can modify it like this:

// Defined somewhere before the form
function handler(url) {
  // Do something with the url.
}

<input type="button" onclick=
  "google.script.run.withSuccessHandler(handler).serverFunc(this.parentNode)">


回答2:

try: return HtmlService.createTemplateFromFile('myPage').evaluate(); More: html service reference



回答3:

I found an answer for my question.

Submit a Form using Google App Script's HtmlService https://script.google.com/d/1i65oG_ymE1lreHtB6WBGaPHi3oLD_-wPd5Ter1nsN7maFAWgUA9DbE4C/edit thanks!