【问题标题】:Ajax POST request failing in DjangoDjango中的Ajax POST请求失败
【发布时间】:2011-07-04 02:43:24
【问题描述】:

我正在发出 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中的“上传”函数中请求没有被识别为“POST”?

提前致谢。

【问题讨论】:

    标签: python ajax django file-upload


    【解决方案1】:

    在您的视图中使用 request.raw_post_data。有点像这样:

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

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

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 2011-07-03
      • 2014-06-29
      • 2015-01-28
      • 1970-01-01
      • 2013-12-26
      • 2015-06-21
      • 2011-11-08
      相关资源
      最近更新 更多