| 123456789101112131415161718192021222324252627282930313233 |
- 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
- class FileUploadView(APIView):
- # 上传图片
- def post(self, request):
- 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 * 10:
- return Response({"code": 2, "msg": "请上传小于10M图片"})
- # if (file_obj.name).split(".")[-1] not in ["jpeg", "jpg", 'png', 'bmp', 'tif','gif', 'flv', 'mp4']:
- # return Response({"code": 2, "msg": "请上传 jpeg jpg png 图片格式"})
- 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'/media/{path}/{file_name}', "code": 0, "msg": "success"})
- except Exception as e:
- return Response({"code": 2, "msg": "图片保存失败,请检查或重试"})
|