Django:文件上传不适用于Ajax [英] Django: File upload not working with Ajax

查看:127
本文介绍了Django:文件上传不适用于Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么,但如果我尝试通过ajax上传文件,它不起作用,但经常要求它。

I don't understand why but if I try to upload file via ajax it does not work but with regular request it does.

打印请求.FILES。

Printed the request.FILES.

#For ajax request
<MultiValueDict: {}>

#For regular request
<MultiValueDict: {u'file': [<TemporaryUploadedFile: IMG_3056.JPG (image/jpeg)>]}>

#Here's my front-end and back-end code
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
...
</form>
function submitForm(target, form){
    $.ajax({
        url:form.attr('action'),
        type:'post',
        data:form.serialize(),
        dataType:"html",
        error:function(data, status, xhr){
            error();
        },
        beforeSend:function(){
            loading();
        },
        success:function(data, status, xhr){
            $(target).html(data);
        },
        complete:function(){
            loadingDone();
        }
    });
}

#views.py

def file_upload(request):
    doc_form = DocumentForm(user = request.user)
    if request.method == 'POST':
        doc_form = DocumentForm(request.POST, request.FILES, user = request.user)
        print request.FILES
        if doc_form.is_valid():
            document = doc_form.save()
    return render_to_response("create_doc.html", {                                                                  'doc_form':doc_form, 
}, context_instance = template.RequestContext(request))


推荐答案

请尝试使用 jquery表单提交插件,我认为它会按照你的需要将文件发送到服务器。

Please try using this jquery form submit plugin, I think it will manage to send the FILE to the server like you need.

(它适用于我的PHP服务器端,没有理由为什么它不会为你工作)

(It works for me for a PHP server side, no reason why it wont work for you too)

这篇关于Django:文件上传不适用于Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆