FastAPI 表单参数与文件上传完全指南:从基础到高级实战 🚀

avatar
cmdragon 渡劫
image image

扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长

探索数千个预构建的 AI 应用,开启你的下一个伟大创意

第一章:表单参数基础

1.1 什么是表单参数?

表单参数是 Web 应用中用于传递用户输入数据的变量,通常通过 HTML 表单提交。在 FastAPI 中,表单参数可以通过 Form 类进行处理。

1
2
3
4
5
6
7
8
from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}

1.2 表单参数的使用

通过 Form 类,可以轻松处理表单参数。

1
2
3
@app.post("/register/")
async def register(name: str = Form(...), email: str = Form(...)):
return {"name": name, "email": email}

示例请求

1
2
3
4
{
"name": "John Doe",
"email": "john.doe@example.com"
}

1.3 表单参数校验

结合 Pydantic 的 Field,可以对表单参数进行数据校验。

1
2
3
4
5
6
from pydantic import Field


@app.post("/contact/")
async def contact(name: str = Form(..., min_length=3), message: str = Form(..., max_length=1000)):
return {"name": name, "message": message}

示例请求

  • 合法:{"name": "John", "message": "Hello"} → 返回联系信息
  • 非法:{"name": "J", "message": "A" * 1001} → 422 错误

1.4 常见错误与解决方案

错误:422 Validation Error
原因:表单参数类型转换失败或校验不通过
解决方案:检查表单参数的类型定义和校验规则。


第二章:文件上传

2.1 什么是文件上传?

文件上传是 Web 应用中用于接收用户上传文件的机制。在 FastAPI 中,文件上传可以通过 File 类进行处理。

1
2
3
4
5
6
7
8
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}

2.2 文件上传的使用

通过 UploadFile,可以轻松处理文件上传。

1
2
3
@app.post("/upload-multiple/")
async def upload_multiple_files(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}

示例请求

  • 单文件:curl -F "file=@test.txt" http://localhost:8000/upload/{"filename": "test.txt"}
  • 多文件:curl -F "files=@test1.txt" -F "files=@test2.txt" http://localhost:8000/upload-multiple/{"filenames": ["test1.txt", "test2.txt"]}

2.3 文件上传的校验

结合 Pydantic 的 Field,可以对上传文件进行大小、类型等校验。

1
2
3
4
5
6
7
from fastapi import File, UploadFile
from pydantic import Field


@app.post("/upload-validated/")
async def upload_validated_file(file: UploadFile = File(..., max_size=1024 * 1024, regex=r"\.(jpg|png)$")):
return {"filename": file.filename}

示例请求

  • 合法:curl -F "file=@test.jpg" http://localhost:8000/upload-validated/{"filename": "test.jpg"}
  • 非法:curl -F "file=@test.pdf" http://localhost:8000/upload-validated/ → 422 错误

2.4 常见错误与解决方案

错误:422 Validation Error
原因:文件上传校验失败
解决方案:检查文件上传的校验规则。


第三章:高级用法与最佳实践

3.1 文件存储

通过 aiofiles,可以异步存储上传的文件。

1
2
3
4
5
6
7
8
9
10
import aiofiles
import os


@app.post("/upload-store/")
async def upload_store_file(file: UploadFile = File(...)):
async with aiofiles.open(f"uploads/{file.filename}", "wb") as out_file:
content = await file.read()
await out_file.write(content)
return {"filename": file.filename}

3.2 文件下载

通过 FileResponse,可以实现文件下载功能。

1
2
3
4
5
6
from fastapi.responses import FileResponse


@app.get("/download/{filename}")
async def download_file(filename: str):
return FileResponse(f"uploads/{filename}")

示例请求

  • 下载:http://localhost:8000/download/test.txt → 返回文件内容

3.3 文件上传优化

通过 StreamingResponse,可以优化大文件上传和下载的性能。

1
2
3
4
5
6
from fastapi.responses import StreamingResponse


@app.post("/upload-stream/")
async def upload_stream_file(file: UploadFile = File(...)):
return StreamingResponse(file.file, media_type=file.content_type)

3.4 常见错误与解决方案

错误:413 Request Entity Too Large
原因:上传文件超过服务器限制
解决方案:调整服务器配置或限制上传文件大小。


课后测验

测验 1:表单参数校验

问题:如何定义一个包含校验规则的表单参数?
答案

1
2
3
4
5
6
7
from fastapi import Form
from pydantic import Field


@app.post("/contact/")
async def contact(name: str = Form(..., min_length=3), message: str = Form(..., max_length=1000)):
return {"name": name, "message": message}

测验 2:文件上传

问题:如何处理多个文件上传?
答案

1
2
3
4
5
6
7
from fastapi import File, UploadFile
from typing import List


@app.post("/upload-multiple/")
async def upload_multiple_files(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}

错误代码应急手册

错误代码典型触发场景解决方案
422类型转换失败/校验不通过检查参数定义的校验规则
413上传文件超过服务器限制调整服务器配置或限制上传文件大小
500未捕获的文件处理异常添加 try/except 包裹敏感操作
400自定义校验规则触发拒绝检查验证器的逻辑条件

常见问题解答

Q:如何处理大文件上传?
A:使用 StreamingResponse 优化性能:

1
2
3
4
5
6
from fastapi.responses import StreamingResponse


@app.post("/upload-stream/")
async def upload_stream_file(file: UploadFile = File(...)):
return StreamingResponse(file.file, media_type=file.content_type)

Q:如何限制上传文件的大小?
A:通过 Filemax_size 参数设置:

1
2
3
4
5
6
from fastapi import File, UploadFile


@app.post("/upload-validated/")
async def upload_validated_file(file: UploadFile = File(..., max_size=1024 * 1024)):
return {"filename": file.filename}

通过本教程的详细讲解和实战项目,您已掌握 FastAPI 表单参数与文件上传的核心知识。现在可以通过以下命令测试您的学习成果:

1
curl -F "file=@test.txt" http://localhost:8000/upload/

余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长,阅读完整的文章:

往期文章归档: