| 1234567891011121314151617181920212223242526272829303132333435 |
- import os
- from rest_framework.views import APIView
- from rest_framework.response import Response
- from rest_framework.parsers import FileUploadParser
- from kedong.settings import MEDIA_ROOT
- import uuid
- import uuid
- from datetime import datetime
- from django.conf import settings
- config = settings.CONFIG
- class FileUploadView(APIView):
- # 上传图片
- def post(self, request):
- server_web = config.get("server_web")
- path = request.data.get("model", "others")
- local_path = os.path.join(MEDIA_ROOT, path)
- os.mkdir(local_path) if not os.path.exists(local_path) else None
- file_obj = request.data['file']
- if file_obj.size > 1024 * 1024 * 200:
- return Response({"code": 2, "msg": "请上传小于200M文件"})
- try:
- stamp = int(datetime.now().timestamp())
- unique_id = uuid.uuid4()
- combined_id = str(stamp) + "-" + str(unique_id)
- file_name = combined_id + "." + ((file_obj.name).split("."))[-1]
- with open(f"{local_path}/{file_name}", 'wb') as f:
- for chunk in file_obj.chunks():
- f.write(chunk)
- return Response({"url": f'{server_web}/media/{path}/{file_name}', "code": 0, "msg": "success"})
- except Exception as e:
- return Response({"code": 2, "msg": "图片保存失败,请检查或重试"})
|