2013-04-04 146 views
5

我在我的django項目中上傳文件時遇到問題。所以問題是:我如何通過jquery ajax將文件傳遞給django視圖?Django ajax jquery文件上傳

在這一刻我有

腳本:

<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: {}>" 

是有可能做到這一點無需外部庫?

+1

您是否嘗試過'文件= request.FILES.get( '文件')' – catherine 2013-04-04 12:33:45

+0

返回對象{消息:空} – vovaminiof 2013-04-04 12:52:35

+0

值傳遞 – vovaminiof 2013-04-04 12:59:33

回答

7

試試這個:

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/

+1

找不到關鍵'文件'的問題是request.FILES爲空 – vovaminiof 2013-04-04 13:03:22

+0

thx爲鏈接:) – vovaminiof 2013-04-05 08:11:19

1
@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> 
+0

無返回到客戶端 – vovaminiof 2013-04-04 13:12:15

+0

刪除此'如果request.is_ajax():'在你的視圖和else語句中。測試如果再次返回到無 – catherine 2013-04-04 13:16:41

+0

完成你的表格在你的模板,以便它會讀取文件通過 – catherine 2013-04-04 13:18:39

0

// 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") 

這應該做的伎倆