Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

FastAPI 如何接收并限制文件上传?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

安装 python-multipart,用 UploadFile 接收 multipart 文件。可以读取文件内容并按业务校验,再持久化。文件名和声明的媒体类型来自客户端。

讲清原理

大文件不要一口气读进内存。控制入口请求体大小,同时限制可接受的文件大小和格式。保存时使用服务端标识和受控目录。

例子与易错点

示例只接受一个小型文本文件,最多读取允许大小再加一字节,并实测超过上限被拒绝。到达处理函数前的上传流量仍要靠入口限制。

from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.testclient import TestClient

app = FastAPI()
limit = 16

@app.post("/notes")
async def read_note(note: UploadFile):
    data = await note.read(limit + 1)
    if len(data) > limit:
        raise HTTPException(status_code=413, detail="note too large")
    try:
        text = data.decode("utf-8")
    except UnicodeDecodeError:
        raise HTTPException(status_code=415, detail="UTF-8 text required")
    return {"characters": len(text)}

with TestClient(app) as client:
    small = client.post("/notes", files={"note": ("note.txt", b"hello", "text/plain")})
    too_large = client.post("/notes", files={"note": ("note.txt", b"x" * 17, "text/plain")})
    assert small.json() == {"characters": 5} and too_large.status_code == 413
    print("5 characters; oversize: 413")

相关题:第 17 题、第 22 题、第 24 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。