Drive.Files.Copy 和 "parents" 不起作用



我正在尝试将团队云端硬盘中的文件复制到新的文件夹位置,也是团队云端硬盘中的文件。我在最后一行代码上收到"找不到文件"错误。newFileID已使用DriveApp.getFileByID和Google API Try-It进行测试进行了检查。

我认为"父母"部分的格式不正确。当我尝试Google API Try-It时,文件被复制到正确的文件夹中。耶!那么谷歌脚本代码有什么问题呢?

https://developers.google.com/drive/api/v3/reference/files/copy#try-it

谷歌脚本代码(不起作用(:

function test() {
// find Teacher's Learner Guides folder
var destinationFolderId = "1qQJhDMlHZixBO9KZkkoSNYdMuqg0vBPU";
var newFile = {
"name": "Learner Guide - test",
"description": "New student learner guide",
"parents": [destinationFolderId]
};
// create duplicate document
var newFileID = "1g6cjUn1BWVqRAIhrOyXXsTwTmPZ4QW6qGhUAeTHJSUs";
var newDoc = Drive.Files.copy(newFile, newFileID);
}

Google API Try-It 代码有效。这是javascript(工作(:

return gapi.client.drive.files.copy({
"fileId": "1g6cjUn1BWVqRAIhrOyXXsTwTmPZ4QW6qGhUAeTHJSUs",
"supportsTeamDrives": true,
"resource": {
"parents": [
"1qQJhDMlHZixBO9KZkkoSNYdMuqg0vBPU"
],
"name": "Learner Test2"
}
})

在Google脚本代码中使用Drive.Files.Copy将复制的文件放入其他文件夹中的有效和/或正确方法是什么?

与请求关联的parents元数据需要云端硬盘 API v2 的ParentReference资源,该资源至少是具有id属性和相关fileId的对象,例如{id: "some id"}.

由于您使用的是团队云端硬盘,因此您必须告知 Google您(即您的代码(知道如何使用supportsTeamDrives可选参数来处理常规云端硬盘和团队云端硬盘之间的相关差异。

注意:

如果提出请求的用户不是团队云端硬盘的成员,并且无权访问家长,则家长列表不会显示在家长列表中。此外,除顶级文件夹外,如果父级列表位于团队云端硬盘中,则父级列表必须只包含一个内容。

假设代码运行程序符合条件,将给定文件复制到给定团队云端硬盘文件夹的最简单代码是:

function duplicate_(newName, sourceId, targetFolderId) {
if (!newName || !sourceId || !targetFolderId)
return;
const options = {
fields: "id,title,parents", // properties sent back to you from the API
supportsTeamDrives: true, // needed for Team Drives
};
const metadata = {
title: newName,
// Team Drives files & folders can have only 1 parent
parents: [ {id: targetFolderId} ],
// other possible fields you can supply: 
// https://developers.google.com/drive/api/v2/reference/files/copy#request-body
};
return Drive.Files.copy(metadata, sourceId, options);
}

延伸阅读:

  • 标准查询参数(这些参数始终可以在可选参数中传递(
  • 部分响应(又名"字段"(

以下是在团队云端硬盘中复制文件的解决方案。 @tehhowch有一篇关于需要可选参数的重要文章(您需要为复制 API v2 使用所有三个参数(。然后,"parents"参数需要一个 File 对象,而不是一个字符串。以下代码的工作原理是复制文件并将其移动到另一个团队云端硬盘文件夹中。

function test() {
// find Teacher's Learner Guides folder
var destFolderId = "1qQJhDMlHZixBO9KZkkoSNYdMuqg0vBPU";
var originalDocID = "1g6cjUn1BWVqRAIhrOyXXsTwTmPZ4QW6qGhUAeTHJSUs";
var destFolder = Drive.Files.get(destFolderId, {"supportsTeamDrives": true});
var newFile = {
"fileId": originalDocID,
"parents": [
destFolder // this needed to be an object, not a string
]
};
var args = {
"resource": {
"parents": [
destFolder // this needed to be an object, not a string
],
"title": "new name of document here"
},
"supportsTeamDrives": true
};
// create duplicate Learner Guide Template document
var newTargetDoc = Drive.Files.copy(newFile, originalDocID, args);
}

最新更新