1

I'm getting image from NodeJS server in form of createReadStream.pipe(res). I'm receiving the response using axios. My question is how do I display that response in image tag in react frontend

My code of backend which is sending the data

router.get('/get_profile_image/:filename',(req,res)=>{
    gfs.files.findOne({filename:req.params.filename},(err,file)=>{
        if(file){
            const readStream=gfs.createReadStream(file.filename)
            readStream.pipe(res);
        }
        else{
            res.status(403).json("no file with this name")
        }
    })
})

My frontend code that receives the response:

import React from 'react';
import './friend.css';
import axios from 'axios';

class Friend extends React.Component{
constructor(props){
    super(props);
    this.state={name:'',picture:[]}

    axios.get(`http://localhost:3002/get_name/${this.props.id}`)
    .then(res=>{
        this.setState({name:res.data})
     })

     axios.get(`http://localhost:3002/image/get_profile_image/
      ${this.props.profile_pic_id}`)
    .then(res=>{

        let picture=new Buffer('binary').toString('base64');
      this.setState({picture:picture})
    })

}
render(){
    console.log(this.state.picture)
    return(
        <div className='inside'>
        <img src={this.state.picture} height='200px' width='200px'/>
        <h3>{this.state.name}</h3>
        <br/>
        </div>
    )
   **strong text**}
  }
 export default Friend;

I am getting nothing displayed in my image tag. I am new to this so I'm finding it difficult to understand the already present answers

Thank You.

Derick Alangi
  • 1,080
  • 1
  • 11
  • 31
Abhinav Singh
  • 302
  • 3
  • 15
  • 1
    Your this.state.picture should be a url ,not an array. Also , you are not using res in the then handler of second axios call. Could you please provide what you are getting in the res object – anuragb26 Nov 23 '18 at 12:24
  • 1
    yes you are correct I solved it with using url. https://stackoverflow.com/questions/47530471/gridfs-how-to-display-the-result-of-readstream-piperes-in-an-img-tag and alos took help from this answer – Abhinav Singh Nov 23 '18 at 14:06

0 Answers0