Why am I Unable to send an image from flask to react using "Send_file"

Viewed 1520

I have created a react app that takes information from a react frontend, sends it to a flask backend with axios, which then processes the information and creates a new image. Im trying to get flask to send the image via send_file to react, but i'm not sure how to do it. I tried saving the image as a png, and then sending it, but the react side can't use that since it's encoded. Here's what's going on: flask:

img = Image.fromarray((np.uint8(cm(img)*255)))
img.save("./thenewimg.png")
return send_file('./thenewimg.png','image/png')

react:

class App extends React.component{
onReturnProcessed = res =>{
    console.log(res.data)
    this.setState({img:res.data})
    this.setState({ImgReturned:true})
    console.log(res.data.img)
    
  }
return axios
        .post(`http://localhost:5000/time`, data, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        })
        .then(res => {
            this.onReturnProcessed(res);
            return res
    });
  }
render(){
return(
      
      <div>
        {this.state.ImgReturned &&
        <img src={(this.state.img)} />}
     </div>

);
}
}


React then sets the state variable "img" to whatever flask returns (namely, the file that flask sends to it). I try to display this state variable in an image html line, but it doesn't let me. Any ideas on how to do this?

note: neither of these is the full code, but I think they give most of what is needed to get an idea of what is done.

Heres some of what is printed in console when the "img" state variable is logged: �m�O<���+����� ��S����i�<��G�~qZrޱ�����s�~9���

1 Answers

You're passing a second positional argument to send_file which it doesn't accept.

I think you're looking for:

return send_file('./thenewimg.png', mimetype='image/png')

However, as you're passing a filename as the first argument it should automatically detect the mimetype, based on that .png extension, so you'd probably get away with just:

return send_file('./thenewimg.png')
Related