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

新手上路,请多包涵

我将图像以 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>: ''}
}

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

<img src="[object Object]">

在 DOM 中。我不知道我哪里错了

编辑

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

原文由 Karthi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 504
1 个回答

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

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

原文由 Matías Bustos 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题