Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

forms - Uploading file using Google Apps Script using HtmlService

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...