Skip to content

What’s the correct way to make the uploaded image file accessible via URL – google drive api v3

I have created a project on Google API’s developer console and enabled Google Drive API.

As well as I have created and downloaded Service account credentials .json file which I am using on Node.js backend server and connecting and uploading image files on google drive.

npm i googleapis
const { google } = require('googleapis');
let privatekey = require("./privatekey.json");

// configure a JWT auth client
let jwtClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    ['https://www.googleapis.com/auth/drive']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
    if (err) {
        console.log(err);
        return;
    } else {
        console.log("Successfully connected to gdrive!");
    }
});

//Google Drive API
let drive = google.drive('v3');
drive.files.list({
    auth: jwtClient,
    q: "name contains 'photo'"
}, function (err, response) {
    if (err) {
        console.log('The API returned an error: ' + err);
        return;
        }
        console.log(response.data);
    var files = response.data.files;
    if (files.length == 0) {
        console.log('No files found.');
    } else {
        console.log('Files from Google Drive:');
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            console.log('%s (%s)', file.name, file.id);
        }
    }
});

let fs = require('fs');
var fileMetadata = {
  name: 'photo.png',
};
var media = {
  mimeType: 'image/jpeg',
  body: fs.createReadStream('files/photo.png'),
};
drive.files.create(
  {
    auth: jwtClient,
    resource: fileMetadata,
    media: media,
    fields: 'id',
  },
  function (err, file) {
    if (err) {
      // Handle error
      console.error(err);
    } else {
      console.log('File Id: ', file.data.id);
    }
  },
);


When I upload the file I get the unique file ID in the response.

On the android application as well as on the front end react application I want to display this image file using URL.

enter image description here


I tried https://drive.google.com/open?id=PASTE YOUR ID HERE as well as http://drive.google.com/uc?export=view&id=PASTE YOUR ID HERE but it says you need access.

enter image description here

I also tried publishAuto:true while uploading image but it didn’t work.

What’s the correct way to make the uploaded image file accessible via URL?

Answer

I solved it by creating a new folder and setting the permission for this folder as

type: anyone
role:  reader

and then uploading images to this folder. When I want to display uploaded images I can display using below URL:

https://drive.google.com/thumbnail?id=YOUR IMAGE ID

Here is the complete code.

const { google } = require('googleapis');
let privatekey = require("./privatekey.json");
let drive = google.drive('v3');

// configure a JWT auth client - login and get the token
let jwtClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    ['https://www.googleapis.com/auth/drive']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
    if (err) {
        console.log(err);
        return;
    } else {
        console.log("Successfully connected to gdrive!");
    }
});

Run this code only once.

//For creating google drive folder
var fileMetadata = {
    'name': 'ProductIcons',
    'mimeType': 'application/vnd.google-apps.folder'
};
drive.files.create({
    auth: jwtClient,
    resource: fileMetadata,
    fields: 'id'
}, function (err, file) {
    if (err) {
        // Handle error
        console.error(err);
    } else {
        console.log('Folder Id: ', file);
    }
});

//For changing folder permission
var fileId = 'FOLDER ID HERE';
var permission =
    {
        'type': 'anyone',
        'role': 'reader',
    }
;

let drive = google.drive('v3');
drive.permissions.create({
    auth: jwtClient,
        resource: permission,
        fileId: fileId,
        fields: 'id',
    }, function (err, res) {
        if (err) {
            // Handle error...
            console.error(err);

        } else {
            console.log('Permission ID: ', res)

        }
    });

And then upload as many images as you want in that folder using below code.

//For uploading image to folder
var folderId = 'FOLDER ID HERE';
let fs = require('fs')
var fileMetadata = {
    'name': 'photo.png',
    parents: [folderId]
};
var media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.png')
};
drive.files.create({
    auth: jwtClient,
    resource: fileMetadata,
    publishAuto:true,
    media: media,
    fields: 'id'
}, function (err, file) {
    if (err) {
        // Handle error
        console.error(err);
    } else {
        console.log('File Id: ', file.data.id);
    }
});