首页 > 解决方案 > 在 ReactJS 中显示来自烧瓶 send_file 函数的图像

问题描述

我使用 Flask send_file 向客户端发送图像,如下所示:

@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 

在 React 中我使用 axios 来读取请求

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)返回这个: 在此处输入图像描述

我需要稍后使用渲染图像,<img src={this.state.images}/>但它不显示任何内容。有什么建议吗?

标签: javascriptreactjsflask

解决方案


你 dataImage.data 是二进制大对象,所以你应该尝试:

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


推荐阅读