使用HtmlService使用Google Apps脚本上传文件

Jan*_*ski 7 google-apps-script

如何将文件上传到谷歌硬盘?我想使用谷歌应用程序脚本 - htmlservice创建一个Web应用程序.我不知道如何将html中的表单指向现有的谷歌应用程序脚本.我很难在谷歌文档中找到一个正确的例子.

我发现了数百个使用UI的示例,但根据https://developers.google.com/apps-script/sunset,它很快就会被弃用.先感谢您!雅努什

<html>
<body>
<form>
   <input type="file"/>
   <input type="button">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

脚本

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

function fileUploadTest()
{
   var fileBlob = e.parameter.upload;
      var adoc = DocsList.createFile(fileBlob);
      return adoc.getUrl();
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*y G 14

让按钮使用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>
Run Code Online (Sandbox Code Playgroud)

在服务器上,让表单处理函数采用一个参数 - 表单本身.来自客户端代码的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();
}
Run Code Online (Sandbox Code Playgroud)

如果您确实想要使用生成并返回的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)">
Run Code Online (Sandbox Code Playgroud)