gpt4 book ai didi

node.js - 创建新文件夹后谷歌驱动器API上传文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:00 24 4
gpt4 key购买 nike

我目前正在关注 Google Drive API 文档,并尝试创建函数创建一个文件夹,然后在创建后将文件上传到其中。目前它只能创建新文件夹,但我要上传到其中的文件不会出现在新创建的文件夹中。我已经启用 api 并与服务帐户共享目标文件夹上传.js

const { google } = require('googleapis');
const fs = require('fs');
const key = require('./test-creds.json');
const drive = google.drive('v3');
const targetFolderId = "1Q_2I3_UpAGs13jEMXGYLgm0dXahnhN4Z"

const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/drive'],
null
);

function uploadFile(childFolderID) {
const fileMetadata = {
name: 'photo.jpg'
}
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('photo.jpg'),
parents: [childFolderID]
}
drive.files.create({
auth: jwtClient,
resource: fileMetadata,
media: media,
fields: 'id'
}, (err, file) => {
if (err) {
console.log(err);
return;
} else {
console.log("imaged uploaded with id ", file.data.id);
console.log(childFolderID);
}
});
}
jwtClient.authorize((authErr) => {
if (authErr) {
console.log(authErr);
return;
}
const folderMetadata = {
name: 'child5',
mimeType: 'application/vnd.google-apps.folder',
parents: [targetFolderId]
};
drive.files.create({
auth: jwtClient,
resource: folderMetadata,
fields: 'id'
}, (err, file) => {
if (err) {
console.log(err);
return;
}
console.log('uploaded folder with id: ', file.data.id);
const childFolderID = file.data.id;
return uploadFile(childFolderID);
})
});

这里是输出:

uploaded folder with id: 1RKu9fxBr-6Pl7F0x5vfrqWb3cgH095BO imaged

uploaded with id 1QGBjXdv6GkgFQDtEsapA_hpAkXGRYEs7

任何帮助将不胜感激:)

最佳答案

我发现我做错了什么

parents: [childFolderID]

应该在 fileMetadata 中,因为它是一种文件类型,所以在 fileUpload 函数中应该是这样的:

const fileMetadata = {
name: 'photo.jpg',
parents: [childFolderID]
}
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('photo.jpg'),
}

关于node.js - 创建新文件夹后谷歌驱动器API上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com