Ad

Using 'request' In Node To Download Image From URL As Buffer And Then Insert Into SQL Database As Varbinary(max)

I'm authenticating users with google/facebook/ms Oauth and I'm then giving them a refresh token. I then use this long-lived refresh token to make requests for short-lived access tokens.

The issue I'm having is my app uses the social profile's photo to display on the frontend but the URL will stop working after the social token expired.

I'm trying to save the user's profile photo to MSSQL DB as varbinary(max) and then serve it back to the front-end with the access tokens.

Here's my code so far around this:

But I'm not sure how to get a binary from the buffer instead of the base64 string?

      request.get(
        { url: req.user._json.picture, encoding: null },
        function(err, res, buffer) {
          res.on('close', () => {
            theRes.send(buffer.toString('base64'));
             return buffer.toString('base64');

               knex('USERS')
                 .update({ photo: photo })
                 .where({ id: req.user.dbUserID })
                 .then(() => {
                   console.log('PHOTO UPDATED');
                   console.log(res);
                   console.log(photo);
                })
                 .catch(err => {
                   console.log('ERROR ADDING PHOTO TO DATABASE');
                   console.log(err);
                 });
             });
          });
        }
      );

EDIT: This is not the same as how to return response from async call, I know how to do that and I'm already doing it in the code example, why on earth would you mark this as a duplicate of that???

Ad

Answer

It can just be stored as a base64 string as it's easier to handle but in the end I just took the dive and implemented blob storage as it's never a good idea to hog a production database with storing actual files in it.

Ad
source: stackoverflow.com
Ad