我正在尝试将图像从 Flask 服务器发送到 Web 脚本。第一个服务器连接到另一个 API 并获取图像。我不想保存此图像,只需将其转发到 Web 应用程序脚本即可。
@app.route('/api/image', methods=['GET'])
def return_image():
r = requests.get(f"{api_url}/image")
return send_file(
BytesIO(r.content),
mimetype='image/jpeg',
as_attachment=True,
attachment_filename='test.jpg')
我正在尝试通过 ajax 请求获取此图像并显示它。
function updateImage() {
$.ajax({
url: "/api/image",
type: "GET",
dataType: 'image/jpg',
success: function (res) {
$(theImg).attr("src", 'data:image/png;base64,'+ res);
M.toast({
html: 'Loading image: Success'
})
},
error: function () {
M.toast({
html: 'Loading image: Fail'
})
}
});
}
我试图让这项工作发挥作用,但未能成功。非常感谢您的帮助。
答案 0 :(得分:0)
乍一看,您的 JS 将 data-uri 写入 src 属性,但 res
实际上是具有 image/png
mimetype 的二进制数据。
因此您要么需要在服务器端对 r.content
进行 base64 编码,here's an example 实际上创建整个 uri 服务器端,然后返回该字符串并让您的 JS 将其添加到 {{1} } 属性。
或者,如果您只是想让您的 JS 支持现有端点,您可以根据 src
响应create a blob,然后 write that to the img tag。