Amir Saleem
Amir Saleem

Reputation: 3140

Convert Binary Media Data to Buffer in Node JS

I am using a third party api which returns the image in Binary Media Data format. After getting this data, I want to upload this to Google Cloud Storage. To do this, I need to convert this data into Buffer. I've tried multiple times but failed.

I am using NodeJS, npm request module to call api to save image to google cloud storage.

Here is the code:

var binaryData = data;
var bufferData = new Buffer(data);
 request({
          method: "POST",
          url: '/endpoint/upload',
          headers: {
                    'cache-control': 'no-cache',
                    'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
                   },
          formData: {
                     filename: {
                     value: fileBase64,
                     options: {
                                filename: 'test.jpg',
                                contentType: 'image/jpeg'
                              }
                     },
                    }
         }, function(err, response, body){
            console.log(body);
         }) 

Upvotes: 1

Views: 1168

Answers (2)

dianasaurio
dianasaurio

Reputation: 21

You need to obtain your file as a stream. Here's a useful post that specifies how to do that with axios. Once you download the file in the server, you can get it as a Buffer with fs.readFile.

Upvotes: 0

Christopher P
Christopher P

Reputation: 1108

Your post request should follow the template described in the documentation. My post request looks like this:

req = https.request({
          method: "POST",
          protocol: 'https:',
          hostname: 'www.googleapis.com',
          path: '/upload/storage/v1/b/[bucket-name]/o?uploadType=media&name=[file-name]',
          headers: {
                        'content-type': 'image/png',
                        'content-length': Buffer.byteLength(data),
                        'authorizatoin': Bearer [bearer-token]
                   }
         }, (res) => {
                console.log(res.statusCode);
                console.log(res.statusMessage);
                console.log(res.headers);
                }
         );

It also looks like you’re lacking authentication. You need to use OAuth 2.0 for Google Cloud Storage. Make sure the Cloud Storage JSON API is enabled too.

Upvotes: 1

Related Questions