简体   繁体   中英

Send image to Google Drive API from NodeJS

I managed to upload text files to google API with this code

google.drive({
  version: 'v3',
  auth
})
var media = {
  mimeType: 'text/plain',
  body: 'text'
}
drive.files.create({
  media: media,
  fields: 'id'
})

But if i try to upload an image as suggested in documentation i'm getting empty file on the drive. Trying to do that this way (file exists and has all privileges)

const drive = google.drive({
  version: 'v3',
  auth
})
var media = {
  mimeType: 'image/png',
  body: fs.createReadStream(path.resolve(__dirname, '../assets/logo.png'))
}
drive.files.create({
  media: media,
  fields: 'id'
})

And when I overviewing request in debug console i see that there was no request body. 在此处输入图片说明

Please, help.

Below is the whole component which is doing the upload

<template>
  <div>
    <button class="btn btn-block btn-success mb-3" @click="connect">Syncronize</button>
    <h3 class="text-center">
      <template v-if="getToken">Sync success</template>
      <template v-else>Sync failed</template>
    </h3>
    <button @click="tryUpload">Test API</button>
  </div>
</template>

<script>
  import OAuth2 from '../classes/OAuth2'
  import { mapActions, mapGetters } from 'vuex'
  const {google} = require('googleapis')

  export default {
    computed: {
      ...mapGetters([
        'getToken'
      ])
    },
    methods: {
      ...mapActions([
        'saveToken'
      ]),
      connect () {
        (async () => {
          let token = await new OAuth2().getToken()
          this.saveToken(token)
        })()
      },
      tryUpload () {
        const auth = new google.auth.OAuth2(
          '....',
          '.....',
          'http://127.0.0.1:42813/callback'
        )
        auth.setCredentials(this.getToken)
        const drive = google.drive({
          version: 'v3',
          auth
        })
        let stream = fs.createReadStream(path.resolve(__dirname, '../assets/logo.png'))
        var media = {
          mimeType: 'image/png',
          body: stream
        }
        drive.files.create({
          media: media,
          fields: 'id'
        }, function (err, file) {
          if (err) {
            console.error(err)
          } else {
            console.log('File Id: ', file.id)
          }
        })
      }
    }
  }
</script>

Try importing the file with require instead

var media = {
  mimeType: 'image/png',
  body: require(path.resolve(__dirname, '../assets/logo.png'))
}

As it is, you are uploading the stream itself, not the file being streamed. If you want to use fs, you should try accessing the stream using the callback inside of the stream.on('{event}' function () {}) method.

It's working for me when I upload a file using arrow functions syntax and async/await (at least for me it's more comfortable like this):

// Your tryUpload Function
const tryUpload = async () => {

    // ...Previous OAuth workflow

    // Build Drive service  
    const drive = google.drive({version: 'v3', auth});
    try {
        const data = await uploadFile(drive);
        console.log(data);
    } catch(err){
        console.log(`There was a problem in the promise ---> ${err}`);
    }
} 

const uploadFile = (drive) =>{
    // Set file metadata and data
    const fileMetadata = {'name': 'testupload.png'};
    const media = {
      mimeType: 'image/png',
      // If it's in the same dir, just pass 'testupload.png'
      body: fs.createReadStream('path/to/testupload.png') 
    };
    // Return the Promise result after completing its task
    return new Promise((resolve, reject) => {
      // Call Files: create endpoint
      return drive.files.create({
        resource: fileMetadata,
        media: media
      },(err, results) => err ? reject(err) : resolve(results))
    });
};

Docs

As a guide to help you. I used these docs:

Files: create .

Perform a simple upload .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM