0

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

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

4 Comments

delete the dash between base and 64 for the value of src attribute
Invalid url error GET:data:image/jpg;base64,255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,226,2,40,73,67,67,95,80,82,79,70,73,76,69,0,1,1,0,0,2,2
because apparently you didn't use the .toString("base64") method that I mentioned in my answer, or maybe you used it but you didn't send the converted data to your frontend. What you have in the url is still the buffer array.
I edited my answer and included the changes you need to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.