如何在Reaction中显示FastAPI的FilerResponse图像? [英] How do I display FastAPI's Fileresponse image inside React?

查看:31
本文介绍了如何在Reaction中显示FastAPI的FilerResponse图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的前端反应代码:

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:

当我console.log(data)then()函数内时,我得到的是:

当我使用FastAPI的内置工具测试API时,我验证了API成功返回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.

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

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

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

但这将意味着在生成的HTML中公开我的后端,并硬编码后端IP。有没有更合适的方法来做到这一点?

推荐答案

我知道如何做到这一点的方法是:在FastAPI中将图像编码为Base64,使用API调用将Base64编码的图像发送到前端,并在Reaction中以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编码的图像。

这篇关于如何在Reaction中显示FastAPI的FilerResponse图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆