我正试图在我的Google Drive中创建一个文件夹,但我真的很挣扎,因为官方文档似乎不正确或过时?
我的代码如下(google-drive.ts):const scopes = ["https://www.googleapis.com/auth/drive"];
const auth = new google.auth.JWT(
process.env.CLIENT_EMAIL,
undefined,
process.env.PRIVATE_KEY,
scopes,
);
auth.authorize((err) => {
if (err) {
console.log(new Error(`Error: ${err}`));
} else {
console.log("Connection established with Google API");
}
});
export const createFolder = async () => {
const drive = google.drive({ version: "v3", auth });
const fileMetaData = {
name: "Invoices",
mimeType: "application/vnd.google-apps.folder",
};
await drive.file.create({
fields: "id"
resource: fileMetaData //This is where the error is, maybe it is because of Typescript but it says resource doesn't exist?
});
};
所以基本上当我尝试创建一个文件夹与file.create()
,根据官方文档,我应该把fileMetaData
在resource
,但Typescript不让我这样做,因为它不存在。
还有,只是一个附带问题。我写的对吗?我使用JWT而不是0Auth,因为我从Google控制台下载的凭证json没有给我一个'secret'。
当我看到你的脚本时,我认为你的脚本中有修改点。那么,下面的修改如何?
:
export const createFolder = async () => {
const drive = google.drive({ version: "v3", auth });
const fileMetaData = {
name: "Invoices",
mimeType: "application/vnd.google-apps.folder",
};
await drive.file.create({
fields: "id"
resource: fileMetaData //This is where the error is, maybe it is because of Typescript but it says resource doesn't exist?
});
};
:
export const createFolder = async () => {
const drive = google.drive({ version: "v3", auth: auth });
const fileMetaData = {
name: "Invoices",
mimeType: "application/vnd.google-apps.folder",
};
const res = await drive.files
.create({
fields: "id",
resource: fileMetaData,
})
.catch((err) => console.log(err));
console.log(res.data);
};
- 运行修改后的脚本时,返回文件夹ID。
注意:
服务帐户创建的文件夹不能直接在您的Google Drive上看到。因为创建的文件夹是用于服务帐户的。所以,当你想在你的浏览器上看到你的Google Drive上创建的文件夹时,请与你的Google帐户共享文件夹,并将文件夹的所有者从服务帐户更改为你的Google帐户。
当您想要将创建的文件夹的所有者从服务帐户转移到您的Google帐户时,您可以通过在使用上述脚本创建文件夹后添加以下脚本来实现这一点。这是一个示例脚本。这样,创建的文件夹可以在你的Google帐户的根目录下看到。
const res = await drive.files .create({ fields: "id", resource: fileMetaData, }) .catch((err) => console.log(err)); console.log(res.data); // Added: Transfer owner of created folder from service account to your Google account. const folderId = res.data.id; if (!folderId) return; const res2 = await drive.permissions .create({ resource: { type: "user", role: "owner", emailAddress: "###", // Please set your email address of Google account. }, fileId: folderId, fields: "id", transferOwnership: true, moveToNewOwnersRoot: true, }) .catch((err) => console.log(err)); console.log(res2.data);
与其他方法一样,下面的流程如何?
手动创建一个新的文件夹在您的谷歌帐户的谷歌驱动器。并且,请将创建的文件夹与服务账户的邮箱共享。并复制文件夹ID。
根据服务帐号新建一个文件夹。在这种情况下,创建文件夹被创建到你的谷歌驱动器上的新文件夹。这样,您就可以在Google Drive中看到服务帐户创建的文件夹。为此,示例脚本如下:
const fileMetaData = { name: "Invoices", mimeType: "application/vnd.google-apps.folder", parents: ["###"], // Please set the folder ID of created folder in your Google Drive. }; const res = await drive.files .create({ fields: "id", resource: fileMetaData, }) .catch((err) => console.log(err)); console.log(res.data);
引用:
- 文件:创建
- 权限:创建