Django中的Ajax POST请求失败

时间:2011-02-25 06:29:34

标签: python ajax django file-upload

我正在制作一个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;

}

有人可以告诉我我错过了什么吗?为什么请求没有在views.py中的“upload”函数中被识别为“POST”?

提前致谢。

1 个答案:

答案 0 :(得分:2)

在视图中使用request.raw_post_data。不知怎的,这样:

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

顺便说一句,我不知道如何通过块获取文件。也许有人知道。