Skip to content Skip to sidebar Skip to footer

How To Display An Image In React From Postgresql

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

Solution 1:

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')});

Solution 2:

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.

Post a Comment for "How To Display An Image In React From Postgresql"