【问题标题】:How to create a new script file via Apps Script & Drive SDK如何通过 Apps Script & Drive SDK 创建新的脚本文件
【发布时间】:2014-11-24 00:44:57
【问题描述】:

尝试通过调用 Apps 脚本中的 Drive SDK 来创建一个包含文件的新项目。

UrlFetchApp 请求中的以下具体内容...

{
  "files": [
    {
      "id":"9basdfbd-749a-4as9b-b9d1-d64basdf803",
      "name":"Code",
      "type":"server_js",
      "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
    },
    {
      "id":"3asf7c0d-1afb-4a9-8431-5asdfc79e7ae",
      "name":"index",
      "type":"html",
      "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    New message!!\n  \u003c/body\u003e\n\u003c/html\u003e"
    }
  ]
}

来自import/export docsexample video Dan 提到调用是针对 Apps 脚本之外的语言,但在使用 Eric 设置授权后请求脚本文件类型列表和这些文件的内容does work oAuth2 库。

我最近的猜测...

function createProject( ) {
  var token = getDriveService().getAccessToken(); // from Eric's oAuth2 lib

  var url = 'https://www.googleapis.com/upload/drive/v2/files?convert=true';

  // Where does this go?
  var files = {
    "files": [
      {
        "name":"Code",
        "type":"server_js",
        "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
      },
      {
        "name":"index",
        "type":"html",
        "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Hello, world!!\n  \u003c/body\u003e\n\u003c/html\u003e"
      }
    ]
  };

  // Where does this go too?
  var metadata = {
    'title': 'script-test1',
    'mimeType': 'application/vnd.google-apps.script',
    "parents": [
      {
        "id": "0B2VkNbQMTnaCODBRVjZQcXBXckU"
      }
    ],
  };

  var options = {
    'headers' : {
      'Authorization': 'Bearer ' +  token,
      'Content-Type': 'application/vnd.google-apps.script+json',
    },
    'method' : 'POST',
    'payload' : files  // probably not right

  };

  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getResponseCode());

}

创建了一个未知类型的无标题​​云端硬盘文件,并且确实将有效负载插入其中,但它没有转换为脚本文件类型。

走另一条路,只是使用...

var file = {
    "title": "Test script",
    "mimeType": "application/vnd.google-apps.script",
    "parents": [
      {
        "id": "[INSERT FOLDER ID HERE]"
      }
    ]
  };

Drive.Files.insert(file);

...引发内部错误。

还知道Drive insert docs 有一个客户端 JS 示例,但不知道应该将其中多少内容(如果可能)转换为服务器端 Apps 脚本。

【问题讨论】:

  • 在您的选项变量中,尝试更改“body:”的有效负载参数,然后忘记元数据。
  • 仍会创建一个未知类型的新云端硬盘文件,但未插入任何文本或任何内容。我没有将body 视为UrlFetchApp docs 中的高级参数,并将payload 解释为等效参数。

标签: api google-apps-script google-drive-api


【解决方案1】:

你快到了,但你有一些错误。您的第一种方法(使用UrlFetch)在options 变量中有一些错误。这是一个 doGet() 函数(在验证授权后)创建一个新的 Apps 脚本项目并将 UrlFetch 响应写入页面:

function doGet() {
  var driveService = getDriveService();
  if (!driveService.hasAccess()) {
    var authorizationUrl = driveService.getAuthorizationUrl();
    var template = HtmlService.createTemplate(
        '<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
        'Refresh the page when authorization complete.');
    template.authorizationUrl = authorizationUrl;
    var page = template.evaluate();
    return page;
  } else {     
    var url = "https://www.googleapis.com/upload/drive/v2/files?convert=true";   
    var requestBody =  {
      "files": [
        {
          "name":"Code",
          "type":"server_js",
          "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
        },
        {
          "name":"index",
          "type":"html",
         "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Created with Apps Script.\n  \u003c/body\u003e\n\u003c/html\u003e"
        }
      ]
    };

    var options = {
      "headers": {
         'Authorization': 'Bearer ' +  driveService.getAccessToken(),
       }, 
      "contentType": "application/vnd.google-apps.script+json",
      "method" : "post",
      "payload": JSON.stringify(requestBody)
    }

    var response = UrlFetchApp.fetch(url, options);
    return HtmlService.createHtmlOutput(response.getContentText());
  }
}

此代码会在根驱动器文件夹中创建一个名为“Untitled”的 Apps 脚本项目文件。 options 对象应指定 POST 作为创建项目的方法(默认为 GET),并且负载需要从 JSON 对象转换为字符串才能被UrlFetch 理解。

或者,您也可以使用 Apps 脚本中的 Advanced Drive Service 而不是 UrlFetch 来做同样的事情。以下代码创建了相同的 Apps 脚本项目(但将其放在指定的文件夹中并将文件命名为“测试脚本”):

function createGoogleFileInFolder3() {  
    var requestBody =  {
      "files": [
        {
          "name":"Code",
          "type":"server_js",
          "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
        },
        {
          "name":"index",
          "type":"html",
          "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Created with Apps Script.\n  \u003c/body\u003e\n\u003c/html\u003e"
        }
      ]
    };

  var resource = {
    "title": "Test script",
    "parents": [
      {
        "id": "<parent folder id here>"
      }
    ]
  };

  var blob = Utilities.newBlob(JSON.stringify(requestBody), "application/vnd.google-apps.script+json");

  Drive.Files.insert(resource, blob, {"convert":"true"});
}

【讨论】:

  • Utilities.newBlob() 是我错过的。由于某种原因,认为 blob 必须来自response.getBlob()。将在我的附加组件中实现。谢谢一吨!
  • 等等,您是手动插入了 unicode \u003c 的转换,还是为此使用了库/映射?
  • 我想使用 Drive.Files.update(recource, fileId, blob) 执行此操作,但我得到“应用程序没有更新应用程序脚本所需的范围。” ?
  • 使用高级驱动器服务不起作用,因为您无法为其设置自定义令牌,也无法让 Apps 脚本为您询问:(
  • upload 方法的可选查询参数convert 现在已弃用。它没有任何功能。 Reference - Parameters
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2013-02-22
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
相关资源
最近更新 更多