将图像blob从Ajax上传到Django

时间:2018-01-04 14:24:38

标签: javascript jquery python ajax django

我正在尝试使用Ajax将图像上传到Django。

Ajax代码:

function sendImage() {
    console.log(blob);
    var fd = new FormData();
    fd.append('image', blob);
    var tet = $.ajax({
        url: '/login/photoverify/',
        type: 'POST',
        data: fd,
        async: false,
        contentType: false,
        processData: false,
        success: function (response) {
            console.log(response.driverBeacon);
            document.getElementById('username').setAttribute('value', response.username);
        },
        error: function (error) {
            console.log(error);
        }
    }).responseText;
}

Django代码:

def imageVerify(request):
    if request.method == 'POST':
        log.info('Inside imageVerify')
        myform = forms.Form(request.POST, request.FILES)
        log.info("Done loading form")
        if myform.is_valid():
            log.info(myform.cleaned_data)
            file = myform.cleaned_data['image']

但是myform.cleaned_data是空的。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您尚未将request.FILES传递给表单实例化。

myform = forms.Form(request.POST, request.FILES)

您可能还需要在contentType: 'multipart/form-data'来电中设置$.ajax()

答案 1 :(得分:1)

解决:

 def imageVerify(request):
if request.method == 'POST':
    log.info('Inside imageVerify')
    myform = forms.Form(request.POST, request.FILES)
    log.info("got Myform")
    file = myform.files['image']