Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delegate file upload management to default_storage. #173

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 14 additions & 21 deletions mdeditor/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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配置,当用户设置了其他配置时,此处无效,需要进一步完善
Expand All @@ -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:
Expand All @@ -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)})