import os import json from django.conf import settings from django.http import HttpResponse from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.decorators import login_required from django.core.files.storage import default_storage from django.core.files.base import ContentFile @login_required def markdown_uploader(request): """ Makdown image upload for locale storage and represent as json to markdown editor. """ if request.method == 'POST' and request.is_ajax(): if 'markdown-image-upload' in request.FILES: image = request.FILES['image'] image_types = [ 'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif' ] if image.content_type not in image_types: data = json.dumps({ 'status': 405, 'error': _('Bad image format.') }) return HttpResponse( data, content_type="application/json", status=405) tmp_file = os.path.join(settings.UPLOAD_PATH, image.name) path = default_storage.save(tmp_file, ContentFile(image.read())) img_url = os.path.join(settings.MEDIA_URL, path) data = json.dumps({ 'status': 200, 'link': img_url, 'name': image.name }) return HttpResponse(data, content_type='application/json') return HttpResponse(_('Invalid request!')) return HttpResponse(_('Invalid request!')) # settings.py import time UPLOAD_PATH = 'images/uploads/' + time.strftime("%Y/%m/%d/") MEDIA_URL = '/media/' # urls.py url( r'^api/uploader/$', markdown_uploader, name='markdown_uploader_page' ), # uploader.js var draceditor = $('.form-uploader'); var UploadImage = function() { var form = new FormData(draceditor.closest('form').get(0)); // getCookie: https://docs.djangoproject.com/en/dev/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-is-false form.append('csrfmiddlewaretoken', getCookie('csrftoken')); $.ajax({ url: 'api/uploader/', type: 'POST', data: form, async: true, cache: false, contentType: false, enctype: 'multipart/form-data', processData: false, beforeSend: function() { console.log('Uploading...'); $('.upload-progress').show(); }, success: function (response) { $('.upload-progress').hide(); if (response.status == 200) { console.log(response); }else { try { var error = JSON.parse(response.error); alert('Vailed to upload! ' + error['data']['error'] + ', error_code: ' + error['status']); }catch(error){ alert('Vailed to upload! ' + response.error + ', error_code :' + response.status); } console.log(response); } }, error: function(response) { console.log("error", response); $('.upload-progress').hide(); } }); return false; }