无法从本地 Flask 服务器加载图像到 React 应用程序

问题描述 投票:0回答:1

我正在尝试在我的 React 应用程序中显示一张图像,该图像是我从本地 Flask 服务器的 POST 请求得到的响应。我尝试将它作为字节数组和网址检索,但没有任何效果,当我将鼠标悬停在元素的 src 上时,firefox 的检查器给我一个“无法加载图像”...

我的 Flask POST 方法到此结束:

    output.save("path/to/my/outputs/generated.png", "PNG") 

    return send_file("path/to/my/outputs/generated.png", mimetype='image/png') 

react 中的 src 内容如下:

    <img src="data:image/png:base64,iVBORw0KGgo  etc etc

这是我的获取函数:

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

功能组件:

    const [selfie, setSelfie] = useState(placeholderImage)

    return (
        <>
            ........
         
            <img 
                src={selfie}
                alt={placeholderImage}
                width={768}
                height={768}
            >
            
            </img>
        </>
    )

回到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))

同样的事情:

    src="data:image/png:base64,iVBORw0KGgoAAAANSUhEUgAAAb etc etc     firefox telling me the image could not be loaded

我处理获取的响应的方式:

            .then(response => response.json())
            .then(json =>{     
                setSelfie(`data:image/png:base64,${json["data"]};`)
            })

最后我尝试了在 stackoverflow 上找到的一个东西,我用字节数组图像进行响应,然后将 api 路径提供给我的 src:

            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

反应:

    src="http://localhost:5000/path"     FF could not load image

图像没有任何问题,我在 vscode 中可以很好地看到它们。我没有收到任何内容安全策略或 cors 错误,并且当我将占位符图像直接从存储库加载到它们显示正常的元素时

有人可以帮忙吗?

javascript reactjs flask fetch-api
1个回答
0
投票

通常您可以使用任何 Web 服务器(例如 nginx/apache2)直接提供静态文件 您可以使用此链接作为参考

直接在响应中发送 url 路径,并在前端使用 nginx/apache2 将文件作为静态 url 提供服务

© www.soinside.com 2019 - 2024. All rights reserved.