upload_file.py 1.4 KB

123456789101112131415161718192021222324252627282930313233
  1. import os
  2. from rest_framework.views import APIView
  3. from rest_framework.response import Response
  4. from rest_framework.parsers import FileUploadParser
  5. from kedong.settings import MEDIA_ROOT
  6. import uuid
  7. import uuid
  8. from datetime import datetime
  9. class FileUploadView(APIView):
  10. # 上传图片
  11. def post(self, request):
  12. path = request.data.get("model", "others")
  13. local_path = os.path.join(MEDIA_ROOT, path)
  14. os.mkdir(local_path) if not os.path.exists(local_path) else None
  15. file_obj = request.data['file']
  16. if file_obj.size > 1024 * 1024 * 10:
  17. return Response({"code": 2, "msg": "请上传小于10M图片"})
  18. # if (file_obj.name).split(".")[-1] not in ["jpeg", "jpg", 'png', 'bmp', 'tif','gif', 'flv', 'mp4']:
  19. # return Response({"code": 2, "msg": "请上传 jpeg jpg png 图片格式"})
  20. try:
  21. stamp = int(datetime.now().timestamp())
  22. unique_id = uuid.uuid4()
  23. combined_id = str(stamp) + "-" + str(unique_id)
  24. file_name = combined_id + "." + ((file_obj.name).split("."))[-1]
  25. with open(f"{local_path}/{file_name}", 'wb') as f:
  26. for chunk in file_obj.chunks():
  27. f.write(chunk)
  28. return Response({"url": f'/media/{path}/{file_name}', "code": 0, "msg": "success"})
  29. except Exception as e:
  30. return Response({"code": 2, "msg": "图片保存失败,请检查或重试"})