How to upload images to google drive from NodeJS API

前端 未结 2 1677
北荒
北荒 2021-01-02 14:14

I have written API and got to upload in Heroku server. When I push the data in the Heroku after changes then all the images are gone. I don\'t know why they were not shown.

2条回答
  •  被撕碎了的回忆
    2021-01-02 14:59

    If You want to upload the image to Google Drive using npm package, You can try it that way:

    • Go to that site: Turn on Google Drive API, create credentials.json file, download it and move to working directory.
    • Add googleapis package: yarn add googleapis
    • Create two functions: authorize and uploadFile.
    • Read Your credentials from credentials.json file, call authorize and invoke uploadFile as a callback.

    Code to upload the image:

    const fs = require('fs');
    const { google } = require('googleapis');
    
    // If modifying these scopes, delete token.json.
    const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
    const TOKEN_PATH = 'token.json';
    
    /**
     * Create an OAuth2 client with the given credentials, and then execute the given callback function.
     */
    function authorize(credentials, callback) {
      const {client_secret, client_id, redirect_uris} = credentials.installed;
      const oAuth2Client = new google.auth.OAuth2(
          client_id, client_secret, redirect_uris[0]);
    
      // Check if we have previously stored a token.
      fs.readFile(TOKEN_PATH, (err, token) => {
        if (err) return getAccessToken(oAuth2Client, callback);
        oAuth2Client.setCredentials(JSON.parse(token));
        callback(oAuth2Client);
      });
    }
    /**
    * Describe with given media and metaData and upload it using google.drive.create method()
    */ 
    function uploadFile(auth) {
      const drive = google.drive({version: 'v3', auth});
      const fileMetadata = {
        'name': 'photo.jpg'
      };
      const media = {
        mimeType: 'image/jpeg',
        body: fs.createReadStream('files/photo.jpg')
      };
      drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
      }, (err, file) => {
        if (err) {
          // Handle error
          console.error(err);
        } else {
          console.log('File Id: ', file.id);
        }
      });
    }
    
    fs.readFile('credentials.json', (err, content) => {
      if (err) return console.log('Error loading client secret file:', err);
      // Authorize a client with credentials, then call the Google Drive API.
      authorize(JSON.parse(content), uploadFile);
    });
    

    Check also official doc: Node.js quickstart, Uploading files

提交回复
热议问题