
正文
FastAPI 学习之路(十八)表单与文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
系列文章:
FastAPI 学习之路(一)fastapi--高性能web开发框架
FastAPI 学习之路(二)
FastAPI 学习之路(三)
FastAPI 学习之路(四)
FastAPI 学习之路(五)
FastAPI 学习之路(六)查询参数,字符串的校验
FastAPI 学习之路(七)字符串的校验
FastAPI 学习之路(八)路径参数和数值的校验
FastAPI 学习之路(九)请求体有多个参数如何处理?
FastAPI 学习之路(十)请求体的字段
FastAPI 学习之路(十一)请求体 - 嵌套模型
FastAPI 学习之路(十二)接口几个额外信息和额外数据类型
FastAPI 学习之路(十三)Cookie 参数,Header参数
FastAPI 学习之路(十四)响应模型
FastAPI 学习之路(十五)响应状态码
FastAPI 学习之路(十六)Form表单
FastAPI 学习之路(十七)上传文件
我们首先要安装表单或者文件处理的依赖
pip install python-multipart
我们去实现下上传和form表单的组合使用
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(...), one: UploadFile = File(...),
token: str = Form(...)
):
return {
"filesize": len(file),
"token": token,
"one_content_type": one.content_type,
}
我们去看下接口请求试试。

声明文件可以使用 bytes 或 UploadFile。可在一个路径操作中声明多个 File 与 Form 参数,但不能同时声明要接收 JSON 的 Body 字段。因为此时请求体的编码为 multipart/form-data
当然我们也可以上传多个文件,实现也很简单。代码如下
from fastapi import FastAPI, File, Form, UploadFile
from typing import List
app = FastAPI()@app.post("/files/")
async def create_file(
file: bytes = File(...), one: List[UploadFile] = File(...),
token: str = Form(...)
):
return {
"filesize": len(file),
"token": token,
"one_content_type": [file.content_type for file in one],
}
我们看下测试结果


多个文件上传也是可以的,也是简单的。
文章首发在公众号,欢迎关注。







