from django.shortcuts import render from ninja import Router from django.http import JsonResponse from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from django.conf import settings import os import uuid from datetime import datetime # Create your views here. router = Router(tags=['content']) @csrf_exempt @require_http_methods(["POST"]) def custom_upload_file(request): """ 自定义 CKEditor 5 上传视图 支持:图片 + PDF / Word / Excel / ZIP 等所有文件 """ file = request.FILES.get('upload') if not file: return JsonResponse({"error": "请选择文件"}, status=400) # 安全处理文件名(避免中文/特殊字符报错) ext = file.name.split('.')[-1].lower() filename = f"{uuid.uuid4().hex}_{datetime.now().strftime('%Y%m%d%H%M%S')}.{ext}" # 保存路径 upload_dir = os.path.join(settings.MEDIA_ROOT, 'uploads') os.makedirs(upload_dir, exist_ok=True) file_path = os.path.join(upload_dir, filename) # 保存文件 with open(file_path, 'wb+') as f: for chunk in file.chunks(): f.write(chunk) # 返回文件 URL(CKEditor 规范格式) file_url = f"{settings.MEDIA_URL}uploads/{filename}" return JsonResponse({ "url": file_url, "default": file_url })