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

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

问题描述

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

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 它很快就会被弃用。
先谢谢您!
Janusz

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

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

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