diff --git a/mdeditor/views.py b/mdeditor/views.py index 9612a59..2bf30bd 100644 --- a/mdeditor/views.py +++ b/mdeditor/views.py @@ -2,11 +2,13 @@ import os import datetime +from django.core.files.base import ContentFile +from django.core.files.storage import default_storage from django.views import generic -from django.conf import settings from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator + from .configs import MDConfig # TODO 此处获取default配置,当用户设置了其他配置时,此处无效,需要进一步完善 @@ -22,7 +24,6 @@ def dispatch(self, *args, **kwargs): def post(self, request, *args, **kwargs): upload_image = request.FILES.get("editormd-image-file", None) - media_root = settings.MEDIA_ROOT # image none check if not upload_image: @@ -44,28 +45,20 @@ def post(self, request, *args, **kwargs): 'url': "" }) - # image floder check - file_path = os.path.join(media_root, MDEDITOR_CONFIGS['image_folder']) - if not os.path.exists(file_path): - try: - os.makedirs(file_path) - except Exception as err: - return JsonResponse({ - 'success': 0, - 'message': "上传失败:%s" % str(err), - 'url': "" - }) - - # save image file_full_name = '%s_%s.%s' % (file_name, '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now()), file_extension) - with open(os.path.join(file_path, file_full_name), 'wb+') as file: - for chunk in upload_image.chunks(): - file.write(chunk) + full_path = os.path.join(MDEDITOR_CONFIGS['image_folder'], file_full_name) + + try: + default_storage.save(full_path, ContentFile(upload_image.read())) + except Exception as err: + return JsonResponse({ + 'success': 0, + 'message': "上传失败:%s" % str(err), + 'url': "" + }) return JsonResponse({'success': 1, 'message': "上传成功!", - 'url': os.path.join(settings.MEDIA_URL, - MDEDITOR_CONFIGS['image_folder'], - file_full_name)}) + 'url': default_storage.url(full_path)})