Hus*_*hab 6 python image flask reactjs
我正在尝试将一个随机生成的图像从 Flask API 发送到我的 React 前端。我开始时每次将图像生成到文件系统时都将其保存,然后尝试使用 react 访问它,但这不适用于生产版本。现在我正在使用 Flask 的 send_file(),但我不确定我在前端做错了什么,因为这是我的第一个 React 项目。
在烧瓶中我有:
@main.route('/get-image', methods=['GET'])
def get_image():
image_array = generate_random_image()
img = Image.fromarray(image_array)
img.save('img.png')
return send_file('img.png', 'image/png')
Run Code Online (Sandbox Code Playgroud)
并在前端
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
image: '/get-image'
};
}
updateImage() {
fetch("/get-image").then(response => {
this.setState({image: /** not sure what to have here **/});
})
}
render() {
return (
<div className="App">
<Container>
<Row>
<Col>
<Image src={this.state.image} rounded/>
</Col>
</Row>
<Row>
<Container>
<Container>
<Row>
<Col>
<Button onClick={() => this.updateImage()}>Original</Button>
</Col>
</Row>
</Container>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
可能值得注意的是,我正在运行 Reactlocalhost:3000
并在localhost:5000
. 我"proxy": "http://localhost:5000"
在我package.json
的 React 目录中。
有什么建议吗?我在反应端尝试了很多东西,但没有一个奏效。我在做一些根本错误的事情吗?
小智 0
如果您希望 Flask 端点返回图像,则无需先将其保存到文件中。您可以在设置适当的标头后直接返回图像,最重要的是content-type
:
from flask import request
@app.route("/get-image")
def image_endpoint():
...
request.headers["content-type"] = "image/png"
image = get_random_png_image_as_bytes()
return image
Run Code Online (Sandbox Code Playgroud)
然后就可以直接加载图片了:
<img src="http://localhost:5000/get-image" />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1104 次 |
最近记录: |