Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

node.js - How to show base64 image in react?

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>: ''}
}

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

<img src="[object Object]">

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

EDIT

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

});

model

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

});

export default mongoose.model('Image', ImageSchema);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}`}/>: ''}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...