使用Google Apps Script和HtmlService上传文件

9
我该如何上传文件到谷歌云端硬盘? 我想使用谷歌应用脚本-htmlservice创建一个Web应用程序。 我不知道如何将HTML表单指向现有的谷歌应用脚本。 我很难在谷歌文档中找到正确的示例。
我发现有数百个使用UI的示例,但根据 https://developers.google.com/apps-script/sunset 的说明,它将很快被弃用。 提前感谢! Janusz
<html>
<body>
<form>
   <input type="file"/>
   <input type="button">
</form>
</body>
</html>

脚本

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

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

GUI构建器将被弃用(以及UiApp中的一些小部件),但不会废除UiApp本身... - Serge insas
请注意,UiApp 的其余部分并未过时,并将继续发挥作用。尽管如此,我们建议您将用户界面迁移到 Html Service,因为它将在长期内提供最佳的功能和支持组合。 - Janusz Chudzynski
3个回答

16

使用google.script.run使按钮运行服务器端函数,并将整个表单作为唯一参数传递。(在按钮的onClick中,“this”是按钮,因此“this.parentNode”是表单。)确保给文件输入命名。

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

在服务器端,让您的表单处理函数接受一个参数-表单本身。来自客户端代码的HTML表单将转换为等效的JavaScript对象,其中所有命名字段都是字符串属性,除了文件将成为blob。

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

如果您真的想使用您正在生成和返回的URL,请确保将成功处理程序添加到google.script调用中。您可以像这样进行修改:

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

当我查看fileBlob时,它只是10个字节的文本 - “FileUpload”。你知道我错过了什么吗? - Andrew Roberts

0

尝试:返回HtmlService.createTemplateFromFile('myPage').evaluate(); 更多信息:html服务参考


0
我找到了我的问题的答案。
以下是使用Google App Script的HtmlService提交表单的链接Submit a Form using Google App Script's HtmlService
下面是Google App Script链接中的代码:
function doGet(e) {
  var template = HtmlService.createTemplateFromFile('Form.html');
  template.action = ScriptApp.getService().getUrl();
  return template.evaluate();
}

function doPost(e) {
  var template = HtmlService.createTemplateFromFile('Thanks.html');
  template.name = e.parameter.name;
  template.comment = e.parameter.comment;
  template.screenshot = e.parameter.screenshot;
  return template.evaluate();
}

https://script.google.com/d/1i65oG_ymE1lreHtB6WBGaPHi3oLD_-wPd5Ter1nsN7maFAWgUA9DbE4C/edit

谢谢!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接