【问题标题】:How do I display FastAPI's Fileresponse image inside React?如何在 React 中显示 FastAPI 的 Fileresponse 图像?
【发布时间】:2021-08-05 11:13:33
【问题描述】:

这是我的前端 React 代码:

import * as React from 'react';
import { useEffect, useState } from 'react';

import http from './http-common'; // axios

type Photo = {
  filename: string,
  caption: string,
  tags: string[].
};

const BrowserArticle = ({ filename, caption, tags }: Photo) => {
  const [photoFile, setFile] = useState<string>('');

  useEffect(() => {
    http.get(`/api/getImg/${filename}`)
      .then((response) => {
        console.log(typeof response.data); // console output is 'string'
        console.log(response); // see screenshot below
        setFile(data);
      });
  }, []);

  return (
    <div>
      <img src={photoFile} alt={filename} />
      <div>{caption}</div>
      <div>
        {
           tags.map((tag) => tag)
        }
      </div>
    </div>
  );
};

这是我的后端 FastAPI 代码:

from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')

@app.get('/api/getImg/{image_filename}')
async def get_image(image_filename: str) -> FileResponse:
  return FileResponse(f'./static/uploads/{image_filename}')

CORS 已得到处理。当我向服务器发送请求时,成功接收到响应,但无法加载图像。经检查,这是生成的 HTML:

当我在then() 函数中console.log(data) 时,这就是我得到的:

当我使用 FastAPI 的内置工具测试 API 时,我验证了 AP​​I 成功返回 blob:http://192.168.1.201:8000/0a870a00-cf63-43ef-b952-e49770137fdd

我怀疑是axios收到的数据是图片文件本身,所以我尝试改代码如下:

const [photoFile, setFile] = useState<File | null>(null);

// ...

<img src={photoFile === null ? '' : URL.createObjectURL(photoFile)} alt={filename} />

但是当我刷新页面时,我得到TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

我尝试搜索如何正确显示从后端接收的图像,但我发现的唯一结果讨论了如何将图像发送到后端或如何显示正在上传到服务器的图像(即显示选择上传的文件的缩略图通过&lt;input type="file" /&gt;。与这个特定问题无关。有什么想法吗?

更新:当我执行以下操作时,图像显示成功:

<img src={`http://192.168.1.201:8000/api/getImg/${filename}`} alt={filename} />

但这意味着在生成的 HTML 中公开我的后端,并对后端 IP 进行硬编码。有没有更“正确”的方式来做到这一点?

【问题讨论】:

    标签: javascript reactjs typescript jsx fastapi


    【解决方案1】:

    我想出的方法是在 FastAPI 中将图像编码为 base64,通过 API 调用将 base64 编码的图像发送到前端,并在 React 中以 base64 编码格式呈现图像。这是它的一些代码。
    FastAPI 代码(切记不要使用response_model=FileResponse

    with open(imgpath, 'rb') as f:
        base64image = base64.b64encode(f.read())
    return base64image
    

    反应代码。

    <img src={data:image/jpeg;base64,${data}} />
    

    这里,${data} 是 base64 编码的图像。

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 2021-07-31
      • 2018-11-07
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2020-05-06
      相关资源
      最近更新 更多