You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NiceGUI结合requests向FastAPI后端上传文件的问题求助

问题解决:NiceGUI上传文件到FastAPI后端

客户端代码问题点:

  • 请求URL错误:不能用FastAPI的文档页面链接,需直接调用接口/uploadfile/
  • 错误将ui.upload组件赋值给files变量:ui.upload是前端上传组件,不是文件对象,应在handle_upload回调里处理文件发送
  • 读取二进制文件(如PDF)使用decode()会报错:PDF是二进制格式,无需解码,直接以二进制方式发送
  • requests.post未传递文件数据,且调用时机错误

服务端代码问题点:

  • File参数未正确实例化:需写成File(...),而非直接使用File
  • 路径拼接用硬编码反斜杠,跨平台兼容性差且易出错:建议用pathlib拼接路径
  • 未处理文件关闭:上传完成后需关闭文件句柄,避免资源泄漏
  • 接口无返回值:最好返回上传结果或文件路径,方便客户端确认

修正后的客户端代码:

from nicegui import ui, events
import requests

def handle_upload(event: events.UploadEventArguments):
    ui.notify(f'开始上传 {event.name}')
    # 以二进制模式读取文件,直接用于requests上传
    with event.content as f:
        # 构造files参数,key需和服务端参数名一致(此处为"file")
        files = {'file': (event.name, f, event.type)}
        try:
            # 调用正确的接口URL
            response = requests.post('http://127.0.0.1:8000/uploadfile/', files=files)
            if response.status_code == 200:
                ui.notify(f'{event.name} 上传成功!')
                print(response.json())
            else:
                ui.notify(f'上传失败,状态码:{response.status_code}')
        except Exception as e:
            ui.notify(f'上传出错:{str(e)}')

# 仅创建upload组件,无需额外赋值给files
ui.upload(on_upload=handle_upload, label='上传PDF或可读文件', accept='.pdf,.txt,.docx')

ui.run()

修正后的服务端代码:

from fastapi import FastAPI, File, UploadFile
import shutil
from pathlib import Path

app = FastAPI()

# 确保存储目录存在
UPLOAD_DIR = Path('Uploaded Files')
UPLOAD_DIR.mkdir(exist_ok=True)

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    # 使用pathlib拼接路径,避免跨平台问题
    stored_file_path = UPLOAD_DIR / file.filename
    # 读取并写入文件
    with open(stored_file_path, "wb") as stored_file:
        shutil.copyfileobj(file.file, stored_file)
    # 关闭文件句柄
    await file.close()
    # 返回上传结果
    return {
        "filename": file.filename,
        "file_path": str(stored_file_path.resolve()),
        "status": "success"
    }

运行说明:

  1. 先启动FastAPI服务:uvicorn main:app --reload(假设服务端代码存为main.py)
  2. 再启动NiceGUI客户端,选择文件上传即可

内容的提问来源于stack exchange,提问作者Alex Irimia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:33:39