diagnose-backend/diagnose/upload_views.py
pzc-x99 f56b66d8f1 /health/
/error_code_map/
/ec_user/*
/diagnose/*
/admin/*
2025-02-28 23:05:31 +08:00

36 lines
1.4 KiB
Python

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from authentication.authentication import CustomTokenAuthentication
import uuid
import os
from django.conf import settings
from django.http import JsonResponse
from rest_framework import status
class MyProtectedUploadfile(APIView):
authentication_classes = [CustomTokenAuthentication] # 使用自定义的 Token 认证
permission_classes = [IsAuthenticated] # 需要用户认证才能访问
def post(self, request):
user = request.user
uuid_str = str(uuid.uuid4())
save_file_path = os.path.join(settings.BASE_DIR, 'upload_file', user.username, uuid_str)
os.makedirs(os.path.dirname(save_file_path), exist_ok=True)
# 获取上传的文件
uploaded_file = request.FILES.get('file')
if not uploaded_file:
return JsonResponse({"error": "No file uploaded."}, status=status.HTTP_400_BAD_REQUEST)
# 保存文件
try:
with open(save_file_path, 'wb+') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
except:
return JsonResponse({"error": "Error saving file."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return JsonResponse({"message": "File uploaded successfully."}, status=status.HTTP_200_OK)