1

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

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

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.