Search code examples
google-apigoogle-drive-api

Can't see file after uploading it with google drive api


I want to upload a file using google drvie api. The code returns 200 OK but I can't see the file when I logged in to the google drive in browser. The credentials.json is generated from a service_account. This account is associated with the google drive api. The id in parent is copied from the browsers address bar when opened the folder. This folder is also shared with the service account.

const auth = new google.auth.GoogleAuth({
  keyFile: 'credentials.json',
  scopes: ['https://www.googleapis.com/auth/drive.file'],
});

const drive = google.drive({version: 'v3', auth});
    
const fileMetadata = {
    'name': 'test.txt',
    'parents':[{"id":"1yh6V..."}]
};
const media = {
    mimeType: 'text/txt',
    body: fs.createReadStream('test.txt')
};
drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
}, (err, file) => {
    if (err) {
       console.error(err);
    } else {
        console.log('Upload success!');
    }
});

enter image description here


Solution

  • It seems you are using Node.js when uploading a file using Drive API, you can use this:

    const fileMetadata = {
        name: 'test.txt',
        parents:["1yh6V..."]
    };
    const media = {
        mimeType: 'text/plain',
        body: fs.createReadStream('test.txt')
    };
    drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
    }, (err, file) => {
        if (err) {
           console.error(err);
        } else {
            console.log('Upload success!');
        }
    });
    

    Here are the changes:

    1. Replaced your media.mimeType to 'text/plain' for a plain text file, here are the list of supported Export MIMETypes
    2. Replaced your fileMetadata.parents to ["1yh6V..."], based on this create file in a folder using Node.js where parent property was specified

    Note:

    Due to my limitation with my environment platforms available, I wasn't able to replicate your issue. I just look for useful references that could help verify your code.