LQ博客 www.lqblogs.com
arrows
nav

图片src属性直接请求node,返回图片二进制数据可直接显示

作者:LQ 来源:原创 发布时间:2019-12-12 浏览量:3060 评论:0 点赞:3

图片src属性直接请求node,返回图片二进制数据可直接显示。


如果返回图片base64字符串,需要分开操作,先请求node端返回对应的图片base64字符串,再通过JS赋值给图片src属性。


先看node端的核心代码:

const when = require('when');
const request = require("request")

const controller = function (req, res) {
    return when.promise((resolve, reject) => {
        res.set({
            'Content-Type': 'image/png;charset=utf-8',
            'encoding': 'binary',
        })
        let imgUrl = decodeURIComponent(req.query.url || '');//URL解码图片URL过来
        if(imgUrl){
            request.get({
                url: imgUrl,
                encoding: 'binary'
            }, function (err, response, body) {
                if(!body || err){
                    res.send({
                        code: 500,
                        message: "查无图片"
                    })
                }else{
                    res.end(Buffer.from(body, 'binary'));//以二进制数据返回
                    resolve();
                }
            })
        }else{
            resolve();
        }
    })
}
module.exports = controller;

前端可以直接通过img的src属性来请求:

<!--url参数,通过encodeURIComponent('http://example.com/testImg.png')进行URL编码透传给node--> 

<img src="http://example.com/test/getImgByNode?url=http%3A%2F%2Fexample.com%2FtestImg.png">


node
如果你感觉本文章对你有帮助的话,那就点赞、打赏或订阅一下吧
点赞(3)
打赏
倒踩(1)
关闭 感谢您的支持,我会继续努力
微信支付
支付宝支付
扫码打赏,建议金额1-20元
浏览量(3060)
讨论本篇文章(0)
发表评论

最多访问文章

最新文章