upload_file.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  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. from django.conf import settings
  10. config = settings.CONFIG
  11. class FileUploadView(APIView):
  12. # 上传图片
  13. def post(self, request):
  14. server_web = config.get("server_web")
  15. path = request.data.get("model", "others")
  16. local_path = os.path.join(MEDIA_ROOT, path)
  17. os.mkdir(local_path) if not os.path.exists(local_path) else None
  18. file_obj = request.data['file']
  19. if file_obj.size > 1024 * 1024 * 200:
  20. return Response({"code": 2, "msg": "请上传小于200M文件"})
  21. try:
  22. stamp = int(datetime.now().timestamp())
  23. unique_id = uuid.uuid4()
  24. combined_id = str(stamp) + "-" + str(unique_id)
  25. file_name = combined_id + "." + ((file_obj.name).split("."))[-1]
  26. with open(f"{local_path}/{file_name}", 'wb') as f:
  27. for chunk in file_obj.chunks():
  28. f.write(chunk)
  29. return Response({"url": f'{server_web}/media/{path}/{file_name}', "code": 0, "msg": "success"})
  30. except Exception as e:
  31. return Response({"code": 2, "msg": "图片保存失败,请检查或重试"})