Saturday, 9 July 2016

Use Nodejs Request model with google-api-nodejs-client to upload pictures to google Drive

when you try to use Nodejs Request model with google-api-nodejs-client to upload pictures to google Drive, you may get below error:

{ [Error: socket hang up] code: 'ECONNRESET' }

drive.files.create({
  resource: {
    parents: [ folderId ],
    name: 'testimage.png',
    mimeType: 'image/png'
  },
  media: {
    mimeType: 'image/png',
    body: request('http://www.peakestravelelite.co.uk/wp-content/uploads/sites/4/2013/10/UK.jpg') // read streams are awesome!
  }

});

This because request doesn't return a normal stream, you have to do this:

Solution:

var imageRequest = request({url:'http://asset1.cxnmarksandspencer.com/is/image/mands/2643f540b32fe8c6cccdec95b3a2c5239166232f?$editorial_430x430$'});
var Readable = require('stream').Readable;
var imageStream = new Readable().wrap(imageRequest);

drive.files.create({
  resource: {
    parents: [ folderId ],
    name: 'testimage.png',
    mimeType: 'image/png'
  },
  media: {
    mimeType: 'image/png',
    body: imageStream
  }
});


No comments:

Post a comment