如何解决驱动器 api - 未找到写入共享文件夹
我正在使用 google drive api 写入位于共享驱动器中的文件夹。 我创建了一个服务帐户,并将服务帐户添加到具有“内容管理员”权限的文件夹中。
但是,当我尝试使用 api 上传文件时,我不断收到错误消息,指出“未找到文件夹”。 当我尝试在我的个人驱动器上创建一个文件夹并添加具有“编辑器”权限的服务帐户时,同样可以正常工作。
如果我遗漏了什么或按照设计,有人可以帮助我吗?
以下是示例代码片段:
谷歌身份验证:
const driveauth = new google.auth.JWT(gSuiteUser,null,JSON.parse(gSuiteKey),[
'https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.appdata'
])
const drive = google.drive({
version: 'v3',auth: driveauth
});
以下是在谷歌驱动器上上传的代码:
const fileMetadata = {
'name': 'Filename','mimeType': 'application/vnd.google-apps.spreadsheet',parents: [gSuiteFolder],convert: true
};
const media = {
mimeType: 'text/csv',body: csvData
};
drive.files.create({
resource: fileMetadata,media: media,fields: 'id'
},(err,file) => {
if (err) {
// Handle error
console.error(`Failure`);
callback(err);
} else {
console.log('Success',file.data.id);
callback(undefined,"done");
}
});
解决方法
我认为您的委托可能有问题。
// loads credentials from .env file
require("dotenv").config();
import { google } from "googleapis";
function initializeDrive(version = "v3") {
const client_email = process.env.GOOGLE_CLIENT_EMAIL;
// add some necessary escaping so to avoid errors when parsing the private key.
const private_key = process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g,"\n");
// impersonate an account with rights to create team drives
const emailToImpersonate = "some-user@acme-industries.com";
const jwtClient = new google.auth.JWT(
client_email,null,// undefined if you use TypeScript
private_key,["https://www.googleapis.com/auth/drive"],emailToImpersonate
);
return google.drive({
version: version,auth: jwtClient
});
}
或者更简单一些
const auth = new google.auth.JWT({ // JWT instead of GoogleAuth
subject: "me@mycompany.com",// include this property
keyFile: "service-account.json",scopes: [ ... ],})
,
原来我们需要发送额外的属性“supportsAllDrives”为真,如下所示:
drive.files.create({
resource: fileMetadata,media: media,supportsAllDrives: true,fields: 'id'
},(err,file) => {
if (err) {
// Handle error
console.error(`Failure`);
callback(err);
} else {
console.log('Success',file.data.id);
callback(undefined,"done");
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。