我们首先要安装表单或者文件处理的依赖
pip install python-multipart
我们去实现下上传和form表单的组合使用
from fastapi import FastAPI, File, UploadFile, Form
app = FastAPI()
@app.post("/files")
async def create_file(
file: bytes = File(...),
one: UploadFile = File(...),
token: str = Form(...)
):
return {
"filesize": len(file),
"token": token,
"oen_content_type": one.content_type
}
我们去看下接口请求试试。
声明文件可以使用 bytes 或 UploadFile。可在一个路径操作中声明多个 File 与 Form 参数,但不能同时声明要接收 JSON 的 Body 字段。因为此时请求体的编码为 multipart/form-data
当然我们也可以上传多个文件,实现也很简单。代码如下
from fastapi import FastAPI, File, UploadFile, Form
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,
"oen_content_type": [file.content_type for file in one]
}
看下结果:
多个文件上传也是可以的,也是简单的。