Django中Ajax POST请求失败

0 投票
1 回答
881 浏览
提问于 2025-04-16 12:30

我正在进行一个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 个回答

2

在你的视图中使用 request.raw_post_data。大概是这样:

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

顺便说一下,我不知道怎么分块获取文件。也许有人知道。

撰写回答