No Description

views.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -- coding: utf-8 --
  2. """simditor views."""
  3. from __future__ import absolute_import
  4. import os
  5. from datetime import datetime
  6. from django.conf import settings
  7. from django.core.files.storage import default_storage
  8. from django.http import JsonResponse
  9. from django.views import generic
  10. from django.views.decorators.csrf import csrf_exempt
  11. from utils.qiniucdn import qiniu_file_url, upload
  12. from . import image_processing, utils
  13. def get_upload_filename(upload_name):
  14. # Generate date based path to put uploaded file.
  15. date_path = datetime.now().strftime('%Y/%m/%d')
  16. # Complete upload path (upload_path + date_path).
  17. upload_path = os.path.join(settings.SIMDITOR_UPLOAD_PATH, date_path)
  18. if getattr(settings, 'SIMDITOR_UPLOAD_SLUGIFY_FILENAME', True):
  19. upload_name = utils.slugify_filename(upload_name)
  20. return default_storage.get_available_name(os.path.join(upload_path, upload_name))
  21. def upload_handler(request):
  22. files = request.FILES
  23. upload_config = settings.SIMDITOR_CONFIGS.get(
  24. 'upload', {'fileKey': 'upload'})
  25. filekey = upload_config.get('fileKey', 'upload')
  26. uploaded_file = files.get(filekey)
  27. if not uploaded_file:
  28. retdata = {'file_path': '', 'success': False,
  29. 'msg': '图片上传失败,无法获取到图片对象!'}
  30. return JsonResponse(retdata)
  31. image_size = upload_config.get('image_size')
  32. if image_size and uploaded_file.size > image_size:
  33. retdata = {'file_path': '', 'success': False,
  34. 'msg': '上传失败,已超出图片最大限制!'}
  35. return JsonResponse(retdata)
  36. backend = image_processing.get_backend()
  37. if not getattr(settings, 'SIMDITOR_ALLOW_NONIMAGE_FILES', True):
  38. try:
  39. backend.image_verify(uploaded_file)
  40. except utils.NotAnImageException:
  41. retdata = {'file_path': '', 'success': False,
  42. 'msg': '图片格式错误!'}
  43. return JsonResponse(retdata)
  44. key = upload(uploaded_file.read())
  45. if not key:
  46. retdata = {'file_path': key, 'success': False, 'msg': '上传失败,请重试!'}
  47. else:
  48. img_url = qiniu_file_url(key)
  49. retdata = {'file_path': img_url, 'success': True, 'msg': '上传成功!'}
  50. return JsonResponse(retdata)
  51. class ImageUploadView(generic.View):
  52. """ImageUploadView."""
  53. http_method_names = ['post']
  54. def post(self, request, **kwargs):
  55. """Post."""
  56. return upload_handler(request)
  57. UPLOAD = csrf_exempt(ImageUploadView.as_view())