使用 HtmlService 使用 Google Apps 脚本上传文件 [英] Uploading file using Google Apps Script using HtmlService

查看:36
本文介绍了使用 HtmlService 使用 Google Apps 脚本上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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>

脚本

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

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

推荐答案

让按钮使用 google.script.run 运行服务器端功能,将整个表单作为唯一参数传递.(在按钮的 onClick 中,'this' 是按钮,所以 'this.parentNode' 是表单.)确保为文件输入命名.

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>

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

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

如果您确实想使用正在生成和返回的 URL,请务必向 google.script 调用添加成功处理程序.你可以这样修改:

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

这篇关于使用 HtmlService 使用 Google Apps 脚本上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆