0

The app is about taking an image from the user using HTML, sending it via API and then adding it to the db saving it as bytea.

The problem is that I cannot display the image when I need it.

The homepage is where I need to display the images.

axios.get('http://localhost:3333/api/getAllHairdressers').then((result)=>{
  console.log(result.data);
  this.setState({data:result.data})
})
}

log data.result is

counter : 1 cutprice : null description : null id : 32 image : {type: "Buffer", data: Array(438763)} location : null password : "123" salname : null username : "ttt"

So how could I show this image? What do I need to use?

1
  • What a nice surprise, 6 months later! Commented Jun 22, 2018 at 9:21

2 Answers 2

4

Base64 encode it when retrieving it from Postgres:

SELECT ENCODE(byteaColumn,'base64') as base64 FROM...;

Then use a base64 data URL to put it in an img tag:

<img src={`data:image/jpeg;base64,${this.state.data}`} />

If you are unable to modify your DB query, you can base64 encode the buffer in Javascript:

this.setState({data: result.data.toString('base64')});
Sign up to request clarification or add additional context in comments.

2 Comments

this is how i got it from the db
db.any('SELECT * FROM hairdressers WHERE id = $1',[32]).then(function(data) { console.log(data); res.json(data) }).catch(function(error) {})
-1

If you want to handle the transformation on the client side:

Using a base64 string as data URI

<img src={`data:image/png;base64,${Buffer.from(this.state.data).toString('base64')}`} />

Using URL.createObjectURL from the URL Web API to create a src url

<img src={URL.createObjectURL(new Blob([Buffer.from(this.state.data)], {'type': 'image/png'}))} />

However, the latter method needs you to clean up by invoking URL.revokeObjectURL to free resources associated with the created url. Though, it is automatically cleaned when the page reloads or is closed.

Comments

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.