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

Flask 怎样接收文件上传?

查看完整题解

参考回答

直接回答

文件表单用 multipart 编码,Flask 通过 request.files 取得文件。应限制请求体,检查业务允许的格式与内容,再使用服务端生成的文件名存到受控目录。

讲清原理

原始文件名和类型声明都来自客户端。即使用 secure_filename 整理名字,也仍要处理空名、碰撞和内容验证。对需要访问控制的文件,下载由授权接口处理。

例子与易错点

示例只接收 UTF-8 文本,限制正文和文件大小,存到临时目录并检查实际保存内容。生产环境还要根据业务做扫描、隔离和安全下载。

from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4

from flask import Flask, request

with TemporaryDirectory() as temporary:
    app = Flask(__name__)
    app.config["MAX_CONTENT_LENGTH"] = 4096
    destination = Path(temporary)

    @app.post("/notes")
    def upload():
        file = request.files.get("note")
        if file is None:
            return {"error": "note required"}, 400
        data = file.stream.read(1025)
        if len(data) > 1024:
            return {"error": "note too large"}, 413
        try:
            text = data.decode("utf-8")
        except UnicodeDecodeError:
            return {"error": "only UTF-8 text is accepted"}, 415
        if not text.strip():
            return {"error": "empty note"}, 400
        name = uuid4().hex + ".txt"
        with (destination / name).open("xb") as output:
            output.write(data)
        return {"file": name}, 201

    client = app.test_client()
    result = client.post("/notes", data={"note": (BytesIO(b"hello"), "note.txt")})
    assert result.status_code == 201
    assert (destination / result.json["file"]).read_bytes() == b"hello"
    large = client.post("/notes", data={"note": (BytesIO(b"x" * 2000), "note.txt")})
    assert large.status_code == 413
print("note saved; oversized note rejected")

相关题:第 26 题、第 27 题、第 29 题。

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

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