无法从本地Flask服务器加载图片至React应用求助
问题:React无法加载Flask POST请求返回的图片
我在React应用中尝试展示通过POST请求本地Flask服务器获取的图片,试过字节数组和URL两种方式都失败了,Firefox检查器显示“无法加载图片”。
图片本身无问题,可在VS Code中正常查看;未出现内容安全策略(CSP)或跨域资源共享(CORS)错误;直接从仓库加载占位图到img元素可正常显示。运行环境为Windows 10 Enterprise。
尝试1:Flask返回send_file
Flask POST方法末尾代码:
output.save("path/to/my/outputs/generated.png", "PNG") return send_file("path/to/my/outputs/generated.png", mimetype='image/png')
React fetch函数:
fetch( "http://localhost:5000/path", { method: "POST", mode: "cors", body: data } ) .then(response => { let reader = new FileReader(); let blob; reader.onload = (event) => { blob = new Blob([response as unknown as BlobPart], {type: "image/png"}) event.target && setSelfie(event.target.result); reader.readAsDataURL(blob) } })
React函数组件代码:
const [selfie, setSelfie] = useState(placeholderImage) return ( <> ........ <img src={selfie} alt={placeholderImage} width={768} height={768} /> </> )
结果:img的src为data:image/png:base64,iVBORw0KGgo etc etc,Firefox提示“无法加载图片”。
尝试2:Flask返回Base64编码的JSON响应
Flask代码:
with open("path/to/my/outputs/generated.png", "rb") as file: saved_img = file.read() saved_img_b64 = base64.b64encode(saved_img).decode('utf-8') response = {} response['data'] = saved_img_b64 return Response(json.dumps(response))
React响应处理代码:
.then(response => response.json()) .then(json =>{ setSelfie(`data:image/png:base64,${json["data"]};`) })
结果:img的src为data:image/png:base64,iVBORw0KGgoAAAANSUhEUgAAAb etc etc,Firefox仍提示“无法加载图片”。
尝试3:Flask直接返回Base64字符串,React用API路径作为src
Flask代码:
with open("path/to/my/outputs/generated.png", "rb") as file: saved_img = file.read() saved_img_b64 = base64.b64encode(saved_img).decode('utf-8') return saved_img_b64
React img设置:
<img src="http://localhost:5000/path" width={768} height={768} alt="generated image" />
结果:Firefox提示“无法加载图片”。
内容的提问来源于stack exchange,提问作者cudnn_account
相关产品推荐
相关产品推荐

