mamproblem69
mamproblem69

Reputation: 15

How to fetch byte array image from api in React

I'm writing app with React frontend and ASP.NET Core Web API backend. I want to send some image through GET request from API:

[Route("getimage")]
[HttpGet]
public async Task<IActionResult> GetImage()
{
    var objectWithImage = db.SomeTable.SingleOrDefault();

    byte[] image = objectWithImage.SomeImage;

    return Ok(image);
}

As you can see it's pretty simple method that gets image I want from database and sends it to site. The image is saved as byte array.

Now in front I'm trying to fetch this image and display it in <img src={this.state.image}>

class SomeClass extends React.Component {

    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
            image: null,
        }
    }

async getImage() {
    fetch("http://localhost:5000/api/controller/getimage")
    .then(response => response.json())
    .then(data => {
        console.log(data)
        this.setState({
           image: data

       })
   })
   console.log(this.state.image)
}

Obviously it doesn't work, the first console.log is displaying binary data normally, the second log after I setState is saying that image is null.

How to fetch this byte[] with image properly and display it on page? I tried to look through some other similar threads but no fix seems to work. I'm quite new to react any help is appreciated

Upvotes: 1

Views: 13621

Answers (1)

jad
jad

Reputation: 138

You can convert byte array to image by concating "data:image/png;base64," + data; you can say this.setState({image: "data:image/png;base64," + data;})

    async getImage() {
    fetch("http://localhost:5000/api/controller/getimage")
    .then(response => response.json())
    .then(data => {
        console.log(data)
        this.setState({
           image: data

       })
   })
   console.log(this.state.image) // *1
}

*1 line is print null because this happens before this.setState. And this.setState will trigger the render function then your image will show up.

Hope it will help :)

Upvotes: 2

Related Questions