How to upload images to google drive from NodeJS API

我只是一个虾纸丫 提交于 2020-04-11 04:56:17

问题


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. I found some other option like images upload in Google Drive directly and I have gone through relevant documentations. I couldn't find any resources related to this.

Can anyone help me out with references or suggestions to upload files to Google Drive?


回答1:


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




回答2:


@KarlR's answer is helpful, but the code has it's own faults. (The scope does not support for file uploads). Let me explain this step by step so that you can easily upload a file to Google Drive.

Step 1: Go to Google Drive API V3 NodeJS quickstart

Follow the initial steps and see whether it works. Then proceed to the next step.

Step 2: Have a function named uploadFile and change the scope to suit the uploads. The code segment is given below.

In the below example, the file is fetched from files/photo.jpg and is renamed as photo.jpg and uploaded to the root folder of Google Drive.

const fs = require('fs');
const { google } = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
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);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Authorize this app by visiting this url:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Enter the code from that page here: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
            if (err) return console.error('Error retrieving access token', err);
            oAuth2Client.setCredentials(token);
            // Store the token to disk for later program executions
            fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) return console.error(err);
                console.log('Token stored to', TOKEN_PATH);
            });
            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);
});

Step 3: Change the name of the file being uploaded

In the uploadFile funciton, change the name property.

const fileMetadata = {
        'name': 'any_name_you_like'
};

Step 4: Upload different file types

You only have to change the following code segment in the uploadFile function. See mostly used mime types for your preferred file extension.

const media = {
     mimeType: 'any_mime_type',
     body: fs.createReadStream('files/photo.jpg')
};

Step 5: Upload the file to a specific folder on Google Drive

Open the browser and log in to your Google Drive. Go to the specific folder and look at the browser URL. It will look like the following.

https://drive.google.com/drive/u/0/folders/1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl

1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl is the folder ID (parentID). Change the following code segment in the uploadFile function.

const fileMetadata = {
        'name': 'any_file_name',
        parents: ['1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl']
};

Hope this is comprehensive enough for your requirements.



来源:https://stackoverflow.com/questions/51870427/how-to-upload-images-to-google-drive-from-nodejs-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!