Django ajax jquery 文件上传

Posted

技术标签:

【中文标题】Django ajax jquery 文件上传【英文标题】:Django ajax jquery file upload 【发布时间】:2013-03-26 12:20:47 【问题描述】:

我的 django 项目中的文件上传有问题。那么问题来了:如何通过 jquery ajax 将文件传递给 django 视图?

此刻我有

脚本:

<script type='text/javascript'>
$(document).ready(function() 
    var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
    $('#upload').click(function() 
        $.ajax(
            csrfmiddlewaretoken: csrf_token,
            type: 'POST',
            url : '../ajax/upload_file/',
            enctype: "multipart/form-data",
            data  : 
                'file': $('#file').val()
            ,
            success: function(data) 
                console.log(data)
            
        )
    )
)
</script>

模板:

 <form method="" action="" name='upload_form' id='upload_form' >% csrf_token %
    <input type='file' name='file' id='file' />
    <input type='button' value='Upload' id='upload'/>
 </form>

观点:

@csrf_exempt
@xhr_to_json
def verifyFile(request):
    if request.is_ajax():
        file = request.FILES['file']
        return 'message': file
    else: 
        return HttpResponseForbidden()

现在我得到了

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111,      in get_response
response = callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
 File "/home/vova/git/LV-  083_LAMP.git/Testcase_Project/Testcase_Project/views/decorator.py", line 6, in wrapper
   data = func(*args, **kwargs)
  File "/home/vova/git/LV-   083_LAMP.git/Testcase_Project/Testcase_Project/views/testcase.py", line 96, in verifyFile
    request.FILES['file']
  File "/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py", line     258, in __getitem__
    raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
MultiValueDictKeyError: "Key 'file' not found in <MultiValueDict: >"

是否可以在没有外部库的情况下做到这一点?

【问题讨论】:

你试过file = request.FILES.get('file') 返回对象 message: null 网址是正确的。我可以返回任何其他数据,它会工作 same error Key 'file' not found in 【参考方案1】:

试试这个:

def upload(request):
  id = request.POST['id']
  path = '/var/www/pictures/%s' % id
  f = request.FILES['picture']
  destination = open(path, 'wb+')
  for chunk in f.chunks():
    destination.write(chunk)
  destination.close()
  # return status to client
  ...

您可以在此处阅读完整教程:http://www.laurentluce.com/posts/upload-to-django-with-progress-bar-using-ajax-and-jquery/

【讨论】:

问题是 request.FILES 是空的【参考方案2】:
@csrf_exempt
@xhr_to_json
def verifyFile(request):
    if request.is_ajax():
        file = request.FILES['file']
        return HttpResponse(file)
    else: 
        return HttpResponseForbidden()

<form method="POST" action="" name='upload_form' id='upload_form' enctype="multipart/form-data">
    % csrf_token %
    <input type='file' name='file' id='file' />
    <input type='button' value='Upload' id='upload'/>
</form>

【讨论】:

在您的视图和 else 语句中删除此 if request.is_ajax():。测试是否再次返回 None 在您的模板中填写您的表单,以便它可以读取文件传递【参考方案3】:

//html

<form  id = "form_id"   method = "POST" action = "#" enctype="multipart/form-data"> % csrf_token %
                        modelform_filefield
                        <input type = "submit" value="Post"/>
                    </form>

//javascript代码

<script>
    $(function()
    $("#form_id").submit(function()
    var data = new FormData($('#form_id').get(0));
                $.ajax(
                    type:"POST",
                    url: "your_upload_url",
                    data : data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(data)
    alert('success');
                    ,
                    failure: function()
                        $(this).addClass("error");
                    
                );
                return false;
    );
    );
</script>

这将从客户端提取文件和表单数据。 URL 链接到处理和存储文件的视图。

//views.py

def upload(request):
    if request.is_ajax():
        form = <modelFormName>(request.POST, files=request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse("form saved")
        else:
            return HttpResponse("form invalid")

    return HttpResponse("not a ajax request")

这应该可以解决问题

【讨论】:

以上是关于Django ajax jquery 文件上传的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 jquery 和 Ajax 将多个文件字段保存到 django

使用 django ajax jquery 提交一个文件不起作用的表单

Django Crud,Django crd应用程序,Django-ajax Crud,Djano Boilerplate应用程序,姜戈注册,姜戈登录,姜戈文件上传,Crud,Bootstrap,aj

Django(十九)Ajax全套

使用ajax上传时缺少Django文件

取消表单文件上传提交