ai_admin/WebAdmin/upload_avatar.py
2024-09-20 04:29:09 +00:00

37 lines
1.3 KiB
Python
Executable File
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.

import os
import uuid
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .base import logger
@csrf_exempt
@require_http_methods(["POST"])
def upload_avatar(request):
"""
上传图片的接口返回图片URL
"""
try:
if not request.user.is_authenticated:
return JsonResponse({'code': 401, 'message': '用户未登录'}, status=401)
if 'avatar' not in request.FILES:
return JsonResponse({'code': 400, 'message': '没有上传图片'}, status=400)
avatar_file = request.FILES['avatar']
# 保存图片到指定目录
avatar_filename = f"{uuid.uuid4()}.{avatar_file.name.split('.')[-1]}"
avatar_path = os.path.join(settings.MEDIA_ROOT, 'avatars', avatar_filename)
with open(avatar_path, 'wb') as f:
for chunk in avatar_file.chunks():
f.write(chunk)
avatar_url = f"{settings.DOMAIN}{settings.MEDIA_URL}avatars/{avatar_filename}"
return JsonResponse({'code': 200, 'avatar_url': avatar_url})
except Exception as e:
logger.error(f"Error uploading avatar: {str(e)}")
return JsonResponse({"code": 500, "message": str(e)}, status=500)