Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking a Base64 Encoded Image and Sending it with ExpressJS as an Image

I'm working on a Node.JS application that utilizes ExpressJS as a web server.

I want to set up a route /get/thumbnail/by_guid/:guid that will return an image as a real image, not a base64 string, so I can set up the source of an image tag using <img src="/get/thumbnail/by_guid/ABCD" > and the actual image will display.

I'm storing the thumbnails as BLOBs in my database and am retrieving them. When I retrieve them, they become buffers in my node application. I'm then sending those buffers in my route as shown below, where img is a buffer object that contains the image.

router.get('/get/thumbnail/by_guid/:guid', function(req, res){
    image_helper.guidToImage(req.params.guid).then(function(img){
        res.set('Content-Type', 'image/jpeg');
        res.set('Content-Length', img.length);
        res.end(img, 'latin1');
    }, function(err){
        res.err(err);
    });
});

guidToImage returns the image as a buffer.

When I go to the url described by a thumbnail I know at, for instance, /get/thumbnail/by_guid/ABCD, I see a white box like this:

White Box

When I look in the network tab of chrome dev tools, the request looks like this:

enter image description here

The response just shows my base64 string:

enter image description here

And the image shows as broken when I source it:

enter image description here

How can I achieve what I'm trying to do?

I've spent 6 hours trying to get this working right now.

Thanks for the help.

like image 283
user2172205 Avatar asked Nov 07 '16 04:11

user2172205


1 Answers

Changed route to get the binary to show properly.

router.get('/get/thumbnail/by_guid/:guid', function(req, res){
    image_helper.guidToImage(req.params.guid).then(function(img){
        var im = new Buffer(img.toString('binary'), 'base64');

        res.writeHead(200, {
        'Content-Type': 'image/jpg',
        'Content-Length': im.length
        });
        res.end(im);
    }, function(err){
        res.err(err);
    });
});
like image 127
user2172205 Avatar answered Oct 11 '22 16:10

user2172205