javascript - 获取 Base64 编码图像并使用 ExpressJS 将其作为图像发送

标签 javascript html node.js image http

我正在开发一个使用 ExpressJS 作为 Web 服务器的 Node.JS 应用程序。

我要设置路由/get/thumbnail/by_guid/:guid这会将图像作为真实图像返回,而不是 base64 字符串,因此我可以使用 <img src="/get/thumbnail/by_guid/ABCD" > 设置图像标签的来源将显示实际图像。

我将缩略图作为 BLOB 存储在我的数据库中并正在检索它们。当我检索它们时,它们成为我的 Node 应用程序中的缓冲区。然后我在我的 route 发送这些缓冲区,如下所示,其中 img是包含图像的缓冲区对象。

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将图像作为缓冲区返回。

当我转到我知道的缩略图描述的 url 时,例如 /get/thumbnail/by_guid/ABCD ,我看到一个像这样的白框:

White Box

当我查看 chrome 开发工具的网络选项卡时,请求如下所示:

enter image description here

响应仅显示我的 base64 字符串:

enter image description here

当我获取图像时图像显示为损坏:

enter image description here

我怎样才能实现我想做的事情?

我已经花了 6 个小时试图让它现在正常工作。

感谢您的帮助。

最佳答案

更改了使二进制文件正确显示的路径。

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

关于javascript - 获取 Base64 编码图像并使用 ExpressJS 将其作为图像发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40457821/

相关文章:

node.js - Reactjs 要求变量中的图像 url 不起作用

node.js - PhoneGap安装: npm command not found

javascript - Nest.js : initialization of property from controller's superclass

javascript - 使用 vanilla JS 将 rel ="noopener noreferrer nofollow"添加到所有外部链接的最佳方法

javascript - 如何知道 div 的滚动条何时到达底部 - JQuery

html - 强制html元素不比页面宽

javascript - jQueryUI : how to restrict droppable area to multiple divs?

jquery - 如何设置相对于内容的div宽度,忽略父级的宽度

javascript - 编辑复制的内容 slider 以工作

javascript - 如何在 swagger 中设置路由参数的数据类型?