Mrunal Tupe
Mrunal Tupe

Reputation: 340

How can I display buffer data as image in react

How to display image in react. ... ..

function App() {
  const [data, setData] = useState();
  useEffect(()=>{
    const getdata= async()=>{
    const response  = await axios.get('http://localhost:8000')
    setData(response.data)
    }getdata()
   }, [])
return (
  <div>
   {data && <img src={"data:image/jpg;base-64,"+data} alt='image'></img>}  
 </div>
 );
}

Backend

 const schema = mongoose.Schema({
    img:{data:Buffer,contentType:String},
    name:{type: String}
  })
 const imageModel = mongoose.model('images', schema)

 app.get("/", function(req, res, next) {
 imageModel.findOne({}, function(err, image) {
 if (err) { return next(err); }
  res.json(image.img.data);
  });
}); 

Response from backend https://i.sstatic.net/x4cSB.png

Upvotes: 0

Views: 5375

Answers (1)

A_Al3bad
A_Al3bad

Reputation: 114

you can use image.img.data.toString("base64") to convert the buffer from the database to base64 representation. So here is what you need to change in your backend:

app.get("/", function(req, res, next) {
  imageModel.findOne({}, function(err, image) {
  if (err) { return next(err); }

  // Replace the buffer array with base64 data
  const imgBase64 = image.img.data.toString("base64");
  image.img.data = imgBase64;

  // Send the object
  res.json(image.img);
});

Upvotes: 1

Related Questions