How do I display FastAPI#39;s Fileresponse image inside React?(如何在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图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在Reaction中显示FastAPI的FilerResponse图像?
基础教程推荐
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
