Display image from flask send_file function in ReactJS

Viewed 1087

I use Flask send_file to send an image to the client like this:

@app.route('/get-cut-image',methods=["GET"])
def get_cut_img():
   response = make_response(send_file(file_path,mimetype='image/png'))
   response.headers['Content-Transfer-Encoding']='base64'
   return response 

and in React I use axios to read the request

try {
  const dataImage = await axios.get(
    "http://localhost:5000/get-cut-image"
  );
  this.setState({
      images: dataImage.data,
    });
  console.log(dataImage.data);
} catch (error) {
  console.log(error);
}

console.log(dataImage.data) return this: enter image description here

I need to render the image later using <img src={this.state.images}/> but it does not display anything. Any advice?

2 Answers

You dataImage.data is Binary large object, so you should try:

try {
  const dataImage = await axios.get(
    "http://localhost:5000/get-cut-image"
  );
  
  const blob = await dataImage.data.blob()
  const url = URL.createObjectURL(blob)
  this.setState({
      images: url,
    });
  console.log(url);
} catch (error) {
  console.log(error);
}

The image sent from the flask app can be simply displayed by <img src={"http://localhost:5000/get-cut-image"}/>.

Related