Login

Django Ajax Image Uploader

Author:
agusmakmun
Posted:
January 6, 2017
Language:
Python
Version:
1.10
Tags:
ajax django image uploader
Score:
0 (after 0 ratings)

Django Ajax Image Uploader, this what we do for: https://github.com/agusmakmun/dracos-markdown-editor/

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
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;
}

More like this

Comments

Please login first before commenting.