- FastAPI 教程
- FastAPI - 主页
- FastAPI - 简介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 类型提示
- FastAPI - IDE 支持
- FastAPI - REST 架构
- FastAPI - 路径参数
- FastAPI - 查询参数
- FastAPI - 参数验证
- FastAPI - Pydantic
- FastAPI - 请求主体
- FastAPI - 模板
- FastAPI - 静态文件
- FastAPI - HTML 表单模板
- FastAPI - 访问表单数据
- FastAPI - 上传文件
- FastAPI - Cookie 参数
- FastAPI - 标头参数
- FastAPI - 响应模型
- FastAPI - 嵌套模型
- FastAPI - 依赖项
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 数据库
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - Websocket
- FastAPI - FastAPI 事件处理程序
- FastAPI - 挂载子应用
- FastAPI - 中间件
- FastAPI - 挂载 Flask 应用
- FastAPI - 部署
- FastAPI 有用资源
- FastAPI - 快速指南
- FastAPI - 有用资源
- FastAPI - 讨论
FastAPI - 上传文件
首先,要向服务器发送文件,需要将 HTML 表单的 enctype 设为 multipart/form-data,并将 input 类型设为 file 以渲染一个按钮,单击该按钮后,你可以从文件系统中选择文件。
<html>
<body>
<form action="https://:8000/uploader" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit"/>
</form>
</body>
</html>
请注意,表单的 action 参数为端点 https://:8000/uploader,并且 method 设为 POST。
此 HTML 表单使用以下代码作为模板进行渲染 −
from fastapi import FastAPI, File, UploadFile, Request
import uvicorn
import shutil
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/upload/", response_class=HTMLResponse)
async def upload(request: Request):
return templates.TemplateResponse("uploadfile.html", {"request": request})
访问 https://:8000/upload/。你应该会看到包含选择文件按钮的表单。单击该按钮以打开要上传的文件。
上传操作由 FastAPI 中的 UploadFile 函数处理
from fastapi import FastAPI, File, UploadFile
import shutil
@app.post("/uploader/")
async def create_upload_file(file: UploadFile = File(...)):
with open("destination.png", "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {"filename": file.filename}
在 FastAPI 中我们将使用shutil库将接收到的文件复制到服务器位置,文件名为destination.png
广告