创建新文件夹后,Google Drive API上传文件

时间:2019-04-22 08:43:36

标签: node.js google-api

我目前正在关注Google Drive API文档,并尝试创建函数来创建一个文件夹,然后在创建后将文件上传到该文件夹​​。目前,它仅设法创建了新文件夹,但我要上传到该文件的文件没有出现在该新创建的文件夹中。 我已经启用了api并与服务帐户共享了目标文件夹 upload.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);
    })
});

此处是输出:

  

已上传ID为1RKu9fxBr-6Pl7F0x5vfrqWb3cgH095BO的上传文件夹

     

已上传ID为1QGBjXdv6GkgFQDtEsapA_hpAkXGRYEs7

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

我发现我做错了

  

父母:[childFolderID]

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

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