简体   繁体   中英

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:

白盒

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

在此处输入图片说明

The response just shows my base64 string:

在此处输入图片说明

And the image shows as broken when I source it:

在此处输入图片说明

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.

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);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM