33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
"""File upload: images and documents, max 10MB."""
|
|
import os
|
|
import uuid
|
|
from flask import current_app
|
|
from werkzeug.utils import secure_filename
|
|
|
|
ALLOWED_IMAGE_EXT = {"png", "jpg", "jpeg", "gif", "webp"}
|
|
ALLOWED_DOC_EXT = {"pdf", "doc", "docx", "txt", "md"}
|
|
MAX_SIZE = 10 * 1024 * 1024
|
|
|
|
|
|
class FileService:
|
|
@staticmethod
|
|
def save_upload(file, subdir="uploads"):
|
|
if not file or not file.filename:
|
|
return None
|
|
filename = secure_filename(file.filename)
|
|
if not filename:
|
|
filename = str(uuid.uuid4())
|
|
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
|
if ext not in ALLOWED_IMAGE_EXT and ext not in ALLOWED_DOC_EXT:
|
|
return None
|
|
upload_root = current_app.config.get("UPLOAD_FOLDER", "/tmp/chat_uploads")
|
|
dest_dir = os.path.join(upload_root, subdir)
|
|
os.makedirs(dest_dir, exist_ok=True)
|
|
unique = "{}_{}".format(uuid.uuid4().hex, filename)
|
|
path = os.path.join(dest_dir, unique)
|
|
file.save(path)
|
|
if os.path.getsize(path) > MAX_SIZE:
|
|
os.remove(path)
|
|
return None
|
|
return (os.path.join(subdir, unique), path)
|