Jonathan Zier
Jonathan Zier

Reputation: 180

Google Drive API uploading files

I'm trying to figure the google drive api (node.js) out for a client. I need to upload files to their drive. I've decided to use a service account and have the auth working. I'm trying to upload a sample file but I can't find it in my drive. My guess is I need to somehow link it to my drive, but I'm not sure. Here is the code I have based off of an example I found online:

async function upload(){
const drive = google.drive({
    version: 'v3',
    auth: authorize()
});

const res = await drive.files.create({
    requestBody: {
        name: 'Test',
        mimeType: 'text/plain'
    },
    media: {
        mimeType: 'text/plain',
        body: 'Hello World'
    }
}, function (err, file) {
    if (err) {
        // Handle error
        console.error(err);
    } else {
        console.log('File Id: ', file.id);
    }
});

authorize() returns the jwtclient and works fine.

console.log(res) returns file id undefined.

any help would be much appreciated!

Upvotes: 0

Views: 243

Answers (1)

Tanaike
Tanaike

Reputation: 201613

When the response value is retrieved from googleapis for Node.js, please modify your script as follows.

From:

console.log('File Id: ', file.id);

To:

console.log('File Id: ', file.data.id);

Note:

  • In your script, I think that you can also use the following script.

      const res = await drive.files
        .create({
          requestBody: {
            name: "Test",
            mimeType: "text/plain",
          },
          media: {
            mimeType: "text/plain",
            body: "Hello World",
          }
        })
        .catch(console.log);
      if (res) console.log("File Id: ", res.data.id);
    

Reference:

Upvotes: 1

Related Questions