如何在反应中显示 base64 图像?

Kar*_*thi 12 base64 mongodb node.js reactjs

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

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>: ''}
}
Run Code Online (Sandbox Code Playgroud)

我得到了我存储在服务器中的精确 base64 字符串。它返回

<img src="[object Object]">
Run Code Online (Sandbox Code Playgroud)

在 DOM.I 不知道我哪里出错了

编辑

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

});
Run Code Online (Sandbox Code Playgroud)

模型

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

});

export default mongoose.model('Image', ImageSchema);
Run Code Online (Sandbox Code Playgroud)

小智 18

您是否确保在 src 属性中添加编码类型以及 base64 编码值?

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

  • 试过了。什么都没有出现。它返回 &lt;img src="[object Object]"&gt;。this.state.image 中的值是“data:image/png;base64,iVBORw0KGgoAAAAN ......” (3认同)