Files
server/base/views.py
T
ngfchl 777ca50328 update. 完成前端页面展示、列表和详情页
update. 调整融合主菜单与板块
update. 分离新闻模块
2026-04-01 14:17:03 +08:00

46 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
# 返回文件 URLCKEditor 规范格式)
file_url = f"{settings.MEDIA_URL}uploads/{filename}"
return JsonResponse({
"url": file_url,
"default": file_url
})