flask-safe-upload.py
import os
import uuid
from flask import request, abort
from werkzeug.utils import secure_filename
ALLOWED = {"png", "jpg", "jpeg", "webp", "pdf"}
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024 # 5 MB, Flask returns 413 above this
@bp.post("/upload")
def upload():
file = request.files.get("file")
if not file or not file.filename:
abort(400, "No file")
ext = file.filename.rsplit(".", 1)[-1].lower()
if ext not in ALLOWED:
abort(400, "File type not allowed")
name = f"{uuid.uuid4().hex}.{ext}" # never trust the user's filename
file.save(os.path.join(app.config["UPLOAD_FOLDER"], secure_filename(name)))
return {"file": name}, 201