如何在反应中显示base64图像? [英] How to show base64 image in react?

查看:85
本文介绍了如何在反应中显示base64图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将图像以base64格式存储在节点中.然后,我将其接收并存储在变量中.并在标签中显示它,但未显示.从服务器接收到正确的值.在渲染中,如果设置了状态,则函数条件为true.即使未显示,其条件也为真.

I am storing the image in a base64 format in a node. Then I am receiving it and storing in a variable. and show it in the tag but it is not showing. Correct values are receiving from server. In render, function condition is true if the state is set.even if its true its not showing.

getImage() {
    console.log('getImage');
    axios.get(`http://localhost:4000/image/get`).then((result) => {
        this.setState({ image: result })
        console.log(result);
    });
}

render(){
    {this.state.image ? <img src={this.state.image}></img>: ''}
}

我正在获取存储在服务器中的确切base64字符串.它返回

I am getting exact base64 string which i am storing in the server.It returns

<img src="[object Object]">

在DOM中.我不知道我要去哪里错了

in DOM.I don't know where am I going wrong

编辑

router.route('/image/get').get((req, res) => {
    console.log('inside img get');
    Image.find((err, result) => {
        if (err) {
            res.json({ "error": true, "message": "error fetching data" });
        } else {
            // console.log(result);
            res.json(result);
        }
    })

});

模型

const mongoose=require('mongoose');
const Schema=mongoose.Schema;
var ImageSchema=new Schema({
    imageName:{
        type:String
    },
    imageData:{
        type:String
    }

});

export default mongoose.model('Image', ImageSchema);

推荐答案

您确定要在src属性中添加编码类型以及base64编码值吗?

Did you make sure to add the encoding type in the src attribute along with the base64 encoded value?

render(){
    {this.state.image ? <img src={`data:image/png;base64,${this.state.image}`}/>: ''}
}

这篇关于如何在反应中显示base64图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆