2011-02-25 110 views
0

我正在發出Ajax POST請求,並且在我的視圖中沒有得到識別。在Django中發生Ajax POST請求失敗

代碼在views.py:

@csrf_exempt 
def upload(request): 
    if request.method == 'POST': 
     form = UploadFileForm(request.POST, request.FILES) 
     if form.is_valid(): 
     #handle_uploaded_file(request.FILES['file']) 
     f = request.FILES['file'] 
      global globalVarForToTrackUpload 
      global globalFileSizeVariable 
     globalFileSizeVariable = f.size 
     filename = "/static/Data/" + f.name 
     destination = open(filename, 'wb+') 
     for chunk in f.chunks(): 
     destination.write(chunk) 
     globalVarForToTrackUpload += len(chunk) 
     destination.close() 
      #return render_to_response('uploadsuccess.html') 
     allValues = str(globalVarForToTrackUpload) + " : " + str(globalFileSizeVariable) 
     return HttpResponse(allValues) 
    else: 
     form = UploadFileForm() 
    return render_to_response('upload.html', {'form': form}) 

我中間件設置:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.csrf.CsrfResponseMiddleware', 
) 

我的JavaScript函數爲:

function submitForm() 

{ 

    //document.forms["myForm"].submit(); 

    xhrPost = getXhrObject(); 
    var arrFiles = document.getElementById('id_file'); 
    var fileToUpload = arrFiles.files[0]; 
    xhrPost.onreadystatechange = function() { 
     if(xhrPost.readyState == 4 && xhrPost.status == 200) 
      document.getElementById("upload-progress-bar").innerHTML = xhrPost.responseText; 
     else 
      document.getElementById("upload-progress-bar").innerHTML = "processing upload..."; 
    } 

    xhrPost.open("POST","/upload.psp/",true); 

    var boundary = "AJAX--------------" + (new Date).getTime(); 
    var contentType = "multipart/form-data; boundary=" + boundary; 
     xhrPost.setRequestHeader("Content-Type", contentType); 
    xhrPost.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); 

    xhrPost.send(fileToUpload); 

    return false; 

} 

誰能告訴我,我缺少的是什麼?爲什麼請求在view.py中的「上傳」功能中沒有被識別爲「POST」?

在此先感謝。

回答

2

在您的視圖中使用request.raw_post_data。不知怎的,像這樣:

if request.is_ajax(): 
    source = request.raw_post_data 
    #Save or/and modify your file 
else: 
    #As usual 

順便說一句,我不知道如何通過塊獲取文件。也許有人知道。