上传文件参数接收用到 File 和 UploadFile
先安装 python-multipart。
pip install python-multipartFileFile 是继承 Form,所以可以定义和 Form 相同的元数据以及额外的验证
从 fastapi 导入 File
from fastapi import FastAPI, File
app = FastAPI()@app.post("/files/")async def create_file(file: bytes = File()):
return {"file_size": len(file)}File 参数文件作为「表单数据」上传。
如果把路径操作函数参数的类型声明为 bytes,FastAPI 将以 bytes 形式读取和接收文件内容。
创建文件(File)参数的方式与 Body 和 Form 一样:
from fastapi import FastAPI, File
@app.post("/files/")async def create_file(file: bytes = File()):
return {"file_size": len(file)}postman 测试文件上传接口

保存文件到本地可以使用 open方法
@app.post("/files/")
async def create_file(file: bytes = File()):
# 保存文件到本地
with open("xx.jpg", "wb") as f:
f.write(file)
return {"file_size": len(file)}File 是直接继承自 Form 的类。
注意,从 fastapi 导入的 Query、Path、File 等项,实际上是返回特定类的函数。
声明文件体必须使用
File,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
这种方式把文件的所有内容都存储在内存里,适用于小型文件。
不过,很多情况下,UploadFile 更好用。
UploadFile 的文件参数定义文件参数时使用 UploadFile:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/uploadfile/")async def create_upload_file(file: UploadFile):
return {"filename": file.filename}postman 测试接口

UploadFile 与 bytes 相比有更多优势:
spooled 文件:async 接口;SpooledTemporaryFile 对象,可直接传递给其他预期「file-like」对象的库。UploadFile 的属性如下:
filename:
上传文件名字符串(str),例如, myimage.jpg;content_type:
内容类型(MIME 类型 / 媒体类型)字符串(str),例如,image/jpeg;file:
SpooledTemporaryFile( file-like 对象)。
其实就是 Python文件,可直接传递给其他预期 file-like 对象的函数或支持库。UploadFile 支持以下 async 方法,(使用内部 SpooledTemporaryFile)可调用相应的文件方法。
write(data):
把 data (str 或 bytes)写入文件;read(size):
按指定数量的字节或字符(size (int))读取文件内容;seek(offset):
移动至文件 offset (int)字节处的位置;await myfile.seek(0) 移动到文件开头;await myfile.read() 后,需再次读取已读取内容时,这种方法特别好用;close():
关闭文件。因为上述方法都是 async 方法,要搭配「await」使用。
例如,在 async 路径操作函数 内,要用以下方式读取文件内容:
contents = await myfile.read()使用 async 方法时,FastAPI 在线程池中执行文件方法,并 await 操作完成。
下载文件
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
file_content = await file.read() # 读取文件
with open("aa.jpg", "wb") as f:
f.write(file_content)
return {
"filename": file.filename,
"content_type": file.content_type
}FastAPI 的
UploadFile直接继承自 Starlette 的UploadFile,但添加了一些必要功能,使之与 Pydantic 及 FastAPI 的其它部件兼容。
可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
@app.post("/uploadfile/")
async def create_upload_file( file: Union[UploadFile, None] = None):
if not file: return {"message": "No upload file sent"} else: return {"filename": file.filename}设置file 文件必传项
file: UploadFile = File(...)UploadFile您也可以将 File() 与 UploadFile 一起使用,例如,设置额外的元数据:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes = File(description="A file read as bytes")):
return {"file_size": len(file)}
@app.post("/uploadfile/")async def create_upload_file(
file: UploadFile = File(description="A file read as UploadFile"),
):
return {"filename": file.filename}