Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 594
Karthi Avatar asked Jun 26 '19 09:06

Karthi


1 Answers

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}`}/>: ''}
}
like image 191
Matías Bustos Avatar answered Sep 16 '22 14:09

Matías Bustos