Django ajaxuploader 400 badrequest错误

时间:2014-08-22 17:21:49

标签: javascript jquery python django ajax-upload

Submitted.html JS也被document.ready函数

包围
var uploader = new qq.FileUploader({
            action: "{% url 'QCOMLTE:imager' %}",
            element: $('#file-uploader')[0],
            multiple: true,
            onComplete: function(id, fileName, responseJSON) {
                if(responseJSON.success) {
                    alert("success!");
                } else {
                    alert("upload failed!");
                }
            },
            onAllComplete: function(uploads) {
                // uploads is an array of maps
                // the maps look like this: {file: FileObject, response: JSONServerResponse}
                alert("All complete!");
            },
            params: {
                'csrf_token': "{{  csrf_token }}",
                'csrf_name': 'csrfmiddlewaretoken',
                'csrf_xname': 'X-CSRFToken'
            }
        });

html body中的其他地方

<div id="file-uploader">
    <noscript>
        <p>Please enable JavaScript to use file uploader.</p>
    </noscript>
</div>

urls.py

urlpatterns = patterns('',
                   url(r"^Submitted/$", views.HybridDetailView.as_view(), name='Submitted'),
                   url(r'^(?P<object_type>\w+)/process/$', views.process, name='process'),
                   url(r'^(?P<object_type>\w+)/$', views.generic_view, name='generic'),
                   url("$^", views.head, name='head'),
                   url("uploader", views.upload, name= 'imager'),
)

views.py

@AjaxFileUploader
def upload(request):
    response = {'files': []}
    script_dir = os.path.dirname(__file__)
    # Loop through our files in the files list uploaded
    print('request',request)
    print(request.FILES)
    for item in request.FILES.getlist('files[]'):
        file = UploadedFile(item)
        with open(script_dir + '/Excel/' + file.name) as destination:
            for chunk in file.chunks():
                destination.write(chunk)
        response['files'].append(file)
        print('appended')

return HttpResponse(json.dumps(response), content_type='application/json')

还在已安装的应用列表中包含“ajaxuploader”

当我尝试通过按钮提交文件时,它会发送帖子调用但收到400(BAD REQUEST)错误。 它甚至没有从我所知道的到达python,至少不是视图代码。它似乎正确地形成了请求URL

http://localhost:8000/QCOMLTE/uploader?qqfile=powered_by.png

当您转到该URL时,它会发送一条消息,指出仅允许发布呼叫。 这类似于Default django-ajax-uploader with s3 backend gives MalformedXML error 除了我没有使用任何后端,只是尝试抓取文件并将它们保存到目录。

更新8/25/14: 从视图中删除了装饰器。这导致错误未被发送。打印请求后,很明显文件正在发送到GET路径而不是FILE路径。我不知道如何改变这一点。

1 个答案:

答案 0 :(得分:0)

找到此Need a minimal Django file upload example

我之前尝试模仿它,发现FILE和POST请求实际上正在通过,不像我正在使用的ajax / jquery。 JQuery是

       $('#uploadform').submit(function (e){
            console.log('submitting')
            var data = new FormData($('#uploadform').get(0));

            $.ajax({
                type: 'POST',
                url: "{% url 'QCOMLTE:imager' %}",
                data: data,
                success: function(data){console.log(data)},
                error: function(data){console.log(data)},
                cache: false,
                processData: false,
                contentType: false
            });
            e.preventDefault()
        });

除了类型低于URL。 我尝试将其更改为$ .post请求,并且它尝试发布到错误的网址然后... 所以我决定改回来,这次把类型放在ajax调用的顶部。然后它工作了......经过多次测试后仍然可以。