google-api-nodejs-client icon indicating copy to clipboard operation
google-api-nodejs-client copied to clipboard

How to upload file type in nodejs googleapis (in express multer)

Open Thammawat opened this issue 7 years ago • 30 comments

I have a problem in uploding pdf file from from fontend in Nodejs so the problem is how to convert file type to correct form to upload to google drive

my file type is like this

{ fieldname: 'file', originalname: 'test.pdf', encoding: '7bit', mimetype: 'application/pdf', buffer: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 20 e2 e3 cf d3 0a 34 0a 30 0a 6f 62 6a 0a 3c 3c 0a 2f 54 79 70 65 0a 2f 43 61 74 61 6c 6f 67 0a 2f 4e 61 6d 65 73 0a 3c ... >, size: 150251 }

and my code is like this ` const {google} = require('googleapis') const drive = google.drive('v3')

const app = express()
const upload = multer()

    app.post(
      'test-upload-pdf-file',
      upload.single('file'),
      (req, res, next) => {
        drive.files.create({
           resource: { mimeType: 'application/pdf'},
           media: {mimeType: 'application/pdf', body: req.file.buffer},
           fields: 'id'
       }, function (err, file) {

      }
    )`

Thammawat avatar Mar 08 '19 12:03 Thammawat

Hi, @Thammawat I did it the following way. It worked for me. Let me know if it works for you.

app.post('/upload', upload.single('my file'), (req, res, next) => {
    let stream = require('stream');
    let fileObject = req.file;
    let bufferStream = new stream.PassThrough();
    bufferStream.end(fileObject.buffer);
    google.drive({ version: 'v3', auth: oauth2Client })
        .files.create({
            media: {
                mimeType: 'application/pdf',
                body: bufferStream
            },
            'requestBody': {
                'name': 'test.pdf',
                 mimeType: 'application/pdf',
            },
            fields: 'id',
        }).then(function (resp) {
            console.log(resp,'resp');
        }).catch(function (error) {
            console.log(error);
        })
    res.send(`File uploaded`);
});

vishald123 avatar Apr 09 '19 11:04 vishald123

Is there any sample code? I searched but cannot find. @JustinBeckwith

buseodaci avatar Apr 23 '19 13:04 buseodaci

@Thammawat modifying code snippet of @vishald123's answer, requestBody is resource (mimeType should be removed from it, parents can be added to store the file/folder in a specific folder.) refactored code is right here. Source:

app.post('/upload', upload.single('my file'), (req, res, next) => {
  const { google } = require('googleapis');
  const stream = require('stream');
  // const serviceAccount = 'PATH TO SERVICE ACCOUNT';  
  let fileObject = req.file;
  let bufferStream = new stream.PassThrough();
  bufferStream.end(fileObject.buffer);
    // const jWTClient = new google.auth.JWT(
    // serviceAccount.client_email,
    // null,
    // serviceAccount.private_key,
    // ['<COMMA SEPARATED SCOPES WHICH ARE AUTHORIZED>']
    // )
    google.drive({ version: 'v3'})
        .files.create({
            auth: oauth2Client/jWTClient,
            media: {
                mimeType: 'application/pdf',
                body: bufferStream
            },
            resource: {
                name: 'test.pdf',
                // if you want to store the file in the root, remove this parents
                parents: ['folder id in which he file needs to be stored.']
            },
            fields: 'id',
        }).then(function (resp) {
            console.log(resp,'resp');
        }).catch(function (error) {
            console.log(error);
        })
    res.send('File uploaded');
});

Reference to have a look: https://developers.google.com/drive/api/v3/manage-uploads#simple Also, make sure that you're using nodeJS 10.x.x as previous versions will cause issues in stream

Let me know if it doesn't works for you.

hiteshsalavi avatar Jun 12 '19 06:06 hiteshsalavi

@Thammawat modifying code snippet of @vishald123's answer, requestBody is resource (mimeType should be removed from it, parents can be added to store the file/folder in a specific folder.) refactored code is right here. Source:

app.post('/upload', upload.single('my file'), (req, res, next) => {
  const { google } = require('googleapis');
  const stream = require('stream');
  // const serviceAccount = 'PATH TO SERVICE ACCOUNT';  
  let fileObject = req.file;
  let bufferStream = new stream.PassThrough();
  bufferStream.end(fileObject.buffer);
    // const jWTClient = new google.auth.JWT(
    // serviceAccount.client_email,
    // null,
    // serviceAccount.private_key,
    // ['<COMMA SEPARATED SCOPES WHICH ARE AUTHORIZED>']
    // )
    google.drive({ version: 'v3'})
        .files.create({
            auth: oauth2Client/jWTClient,
            media: {
                mimeType: 'application/pdf',
                body: bufferStream
            },
            resource: {
                name: 'test.pdf',
                // if you want to store the file in the root, remove this parents
                parents: ['folder id in which he file needs to be stored.']
            },
            fields: 'id',
        }).then(function (resp) {
            console.log(resp,'resp');
        }).catch(function (error) {
            console.log(error);
        })
    res.send('File uploaded');
});

Reference to have a look: https://developers.google.com/drive/api/v3/manage-uploads#simple Also, make sure that you're using nodeJS 10.x.x as previous versions will cause issues in stream

Let me know if it doesn't works for you.

Hi, I'm able to upload successfully but I can't seem to find the image in my google drive. I'm not sure where my image is uploaded to.

helloitsm3 avatar Jul 09 '19 13:07 helloitsm3

@helloitsm3 If you have provided resource.parents the file should have been uploaded to the directory of the id provided. Or else it will be uploaded to the root directory.

I rather suggest, to look into the Quick Access section of Google Drive

hiteshsalavi avatar Jul 09 '19 13:07 hiteshsalavi

If you have provided resource.parents the file should have been uploaded to the directory of the id provided. Or else it will be uploaded to the root directory.

I rather suggest, to look into the Quick Access section of Google Drive

I tried that. It's not showing up. However, the funny thing is that I am able to get all the images when I try to use google.drive.files.list(). Could it be because I'm using a g_service account?

helloitsm3 avatar Jul 09 '19 13:07 helloitsm3

@helloitsm3 Can you please provide the argument that you provided in google.drive.files.list?

hiteshsalavi avatar Jul 09 '19 13:07 hiteshsalavi

@helloitsm3 Can you please provide the argument that you provided in google.drive.files.list?

const auth = new google.auth.JWT({ email: privateKey.client_email, key: privateKey.private_key, scopes: ["https://www.googleapis.com/auth/drive"] });

google.drive({ version: "v3" }).files.list( { auth: auth, q: "mimeType='image/jpeg'", fields: "nextPageToken, files(id, name)", spaces: "drive", pageToken: pageToken })

helloitsm3 avatar Jul 09 '19 13:07 helloitsm3

@helloitsm3 I would like to see auth definition.

hiteshsalavi avatar Jul 09 '19 13:07 hiteshsalavi

@helloitsm3 I would like to see auth definition.

I included it

helloitsm3 avatar Jul 09 '19 13:07 helloitsm3

In this case, search in google drive owner: privateKey.client_email(put the value) and search.

hiteshsalavi avatar Jul 09 '19 13:07 hiteshsalavi

owner: privateKey.client_email(put the value)

Nope. It's completely empty. There's nothing at all.

helloitsm3 avatar Jul 09 '19 13:07 helloitsm3

Try this.

const auth = new google.auth.JWT(
      accountKey.client_email,
      null,
      accountKey.private_key,
      ["https://www.googleapis.com/auth/drive"],
      'YOUR EMAIL ID'
    );

hiteshsalavi avatar Jul 09 '19 13:07 hiteshsalavi

Try this.

const auth = new google.auth.JWT(
      accountKey.client_email,
      null,
      accountKey.private_key,
      ["https://www.googleapis.com/auth/drive"],
      'YOUR EMAIL ID'
    );

Doesn't seem to work. My email ID returns an error. "Client is unauthroized to retrieve access tokens using this method, or client not authrozied for any of the scopes requested".

helloitsm3 avatar Jul 09 '19 14:07 helloitsm3

Are you using G-Suit email id or your personal email ID?

hiteshsalavi avatar Jul 09 '19 14:07 hiteshsalavi

Try this.

const auth = new google.auth.JWT(
      accountKey.client_email,
      null,
      accountKey.private_key,
      ["https://www.googleapis.com/auth/drive"],
      'YOUR EMAIL ID'
    );

Could it be because I'm using a private key that's link to my service account? Meaning my service account has it's own drive instead of my main account?

helloitsm3 avatar Jul 09 '19 14:07 helloitsm3

Are you using G-Suit email id or your personal email ID?

my personal email ID which I use to create the service account

helloitsm3 avatar Jul 09 '19 14:07 helloitsm3

Service Account does not own Google Drive. It can act as a user. Like you can share a file/folder with the client_email mentioned in service account, It can own a file/folder but not Drive.

Since you are using personal email id, Try this

  1. Create a folder in Drive.
  2. Share the folder with the client_email of the service account.
  3. Upload your files providing resource.parents having value [ID of the folder]. You can get the id of the folder from the URL.

URL format of a directory in Google Drive https://drive.google.com/drive/folders/0B-ExmsZGdWssSWluUkZQb0pWd2M then the ID will be 0B-ExmsZGdWssSWluUkZQb0pWd2M

Code snippet

google.drive({ version: 'v3'})
        .files.create({
            auth: oauth2Client/jWTClient,
            media: {
                mimeType: 'application/pdf',
                body: bufferStream
            },
            resource: {
                name: 'test.pdf',
                // if you want to store the file in the root, remove this parents
                parents: ['0B-ExmsZGdWssSWluUkZQb0pWd2M'] // ID of the folder that you created.
            },
            fields: 'id',
        }).then(function (resp) {
            console.log(resp,'resp');
        }).catch(function (error) {
            console.log(error);
        })```

hiteshsalavi avatar Jul 09 '19 14:07 hiteshsalavi

Service Account does not own Google Drive. It can act as a user. Like you can share a file/folder with the private key mentioned in service account, It can own a file/folder but not Drive.

Since you are using personal email id, Try this

1. Create a folder in Drive.

2. Share the folder with the private key of the service account.

3. Upload your files providing `resource.parents` having value [ID of the folder].
   You can get the id of the folder from the URL.

URL format of a directory in Google Drive https://drive.google.com/drive/folders/0B-ExmsZGdWssSWluUkZQb0pWd2M then the ID will be 0B-ExmsZGdWssSWluUkZQb0pWd2M

Code snippet

google.drive({ version: 'v3'})
        .files.create({
            auth: oauth2Client/jWTClient,
            media: {
                mimeType: 'application/pdf',
                body: bufferStream
            },
            resource: {
                name: 'test.pdf',
                // if you want to store the file in the root, remove this parents
                parents: ['0B-ExmsZGdWssSWluUkZQb0pWd2M']
            },
            fields: 'id',
        }).then(function (resp) {
            console.log(resp,'resp');
        }).catch(function (error) {
            console.log(error);
        })```

OMG! It works. Thank you very much.

helloitsm3 avatar Jul 09 '19 14:07 helloitsm3

Good to know. Keep up doing Interesting things!

hiteshsalavi avatar Jul 09 '19 14:07 hiteshsalavi