Reputation: 3880
I'm currently following Google Drive APIs document and trying to create function create a folder then upload a file to it after creation. Currently it only managed to create new folder but the file i want to upload to it doesn't appear in that newly created folder. I already enable to the api and shared the target folder with the service account 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);
})
});
here the output:
uploaded folder with id: 1RKu9fxBr-6Pl7F0x5vfrqWb3cgH095BO imaged
uploaded with id 1QGBjXdv6GkgFQDtEsapA_hpAkXGRYEs7
any help would be appreciate :)
Upvotes: 4
Views: 1174
Reputation: 3880
i found out what i did wrong the
parents: [childFolderID]
should be in fileMetadata because it's a file type so in fileUpload function it should be this:
const fileMetadata = {
name: 'photo.jpg',
parents: [childFolderID]
}
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('photo.jpg'),
}
Upvotes: 2