Django + Jquery ajax图片上传问题

时间:2015-01-07 14:44:03

标签: jquery ajax django upload image-uploading

所以当我尝试使用Jquery Ajax将图像上传到我的Django 1.7服务器时,我遇到了一些问题。

基本上我在我的开发机器和我的升级机器中获得的行为是不同的,所以即使确定除the file is not being uploaded for certain images之外的问题也变得复杂。

我正在使用runserver而没有网络服务器,基本上当我在我的开发中上传一个BIG / large文件(10MB)时,request.FILES在服务器中空了。

对于2MB文件,我的本地计算机工作正常并使用InMemoryUploadedFile正确上传文件,我在文档中读到small files。 我的暂存中的相同2MB文件无法上传(request.FILES在服务器上空了。)

我的想法已经用完了,有没有人知道可能出错的什么/遗失?

这是我的代码:

服务器:

class AjaxUploadImageView(UpdateView):
    model = Multimedia

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        log.info(
            'Starting image upload process!!'.format(**locals())
        )
        if request.is_ajax():
            response = {}
            log.info(
                'AjaxUploadImageView request.FILES: {request.FILES}'
                .format(**locals())
            )
            if request.FILES.get('source_file'):
                uploaded_img = request.FILES.get('source_file')
                self.object.source_file.save(
                    str(uploaded_img.name), File(uploaded_img)
                )
                log.info(
                    'It was uploaded: {self.object.source_file.url}'
                    .format(**locals())
                )
                response['source_file_url'] = self.object.source_file.url
            else:
                log.error(
                    "There was no 'request.FILES.get('source_file')'!!"
                    .format(**locals())
                )
            return HttpResponse(
                json.dumps(response), content_type="application/json"
            )

        else:
            log.error(
                'There was no AJAX request!!'.format(**locals())
            )

            return HttpResponse(status=400)

我的客户方(只有可能相关的内容):

<script type="text/javascript">
    var $ = django.jQuery;
    $(document).ready(function(){
         // This code needs to live here so that Django's URL Reverse can work

        // CSRF Token generation
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = django.jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getCookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        function sameOrigin(url) {
            // test that a given url is a same-origin URL
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
        }
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                    // Send the token to same-origin, relative URLs only.
                    // Send the token only if the method warrants CSRF protection
                    // Using the CSRFToken value acquired earlier
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        // Read a page's GET URL variables and return them as an associative array.
        function getUrlVars(href)
        {
            if (!href) {
                href = window.location.href;
            }
            var vars = [], hash;
            var hashes = href.slice(href.indexOf('?') + 1).split('&');
            for(var i = 0; i < hashes.length; i++)
            {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

        function ajaxImageUpload(obj_id)
        {
            var formData = new FormData($('form')[0]);
            if (obj_id) {
                $.ajax({
                    url: "{% url 'core:ajax-upload-image' 999 %}".replace(999, obj_id),  //Server script to process data
                    type: 'POST',
                    xhr: function() {  // Custom XMLHttpRequest
                        var myXhr = $.ajaxSettings.xhr();
                        return myXhr;
                    },
                    //Ajax events
{#                    beforeSend: beforeSendHandler,#}
                    success: function(result){
                        if(result.source_file_url){
                            alert("The file was successfully uploaded!");
                        }
                    },
                    // Form data
                    data: formData,
                    //Options to tell jQuery not to process data or worry about content-type.
                    cache: false,
                    contentType: false,
                    processData: false
                });
            }
            else{
                alert("There is no ID");
            }
        }

        $('.available, .empty').click(function(e) {
            e.preventDefault();

            var available_empty_url = $('.available, .empty').children('a').attr('href');
            var available_empty_language = getUrlVars(available_empty_url)['language'];

            if (available_empty_language == 'en'){
                var current_language = 'fr'
            }
            else if (available_empty_language == 'fr'){
                var current_language = 'en'
            }

            var fields_to_save = $("#multimedia_form").serialize();
            var original_id = '{{ original.id }}';
            if (original_id) {
                // Editing
                var url = "{% url 'core:update-multimedia-admin-tab-info' 999 %}".replace(999, original_id) + "?language=" + current_language;
                $.post(url, fields_to_save, function(data,status){
                    if (status =='success') {
                        console.log("This tab was updated");
                        var redirect_url = "{% url 'admin:core_multimedia_change' 999 %}".replace(999, data.obj_id) + '?language=' + available_empty_language;
                        ajaxImageUpload(data.obj_id);
                        window.location.href = redirect_url;
                    }
                });
            }
        });
    });
</script>

任何想法?

1 个答案:

答案 0 :(得分:0)

我最后通过添加async: false来修复此问题,以便在图片上传时使jquery调用同步。在两者上测试了10MB图像并且它可以工作