简体   繁体   English

如何从我的视图中的Formdata对象获取数据?

[英]How to get data from a Formdata object in my views?

My AJAX call sends a FormData object with an uploaded image data inside it: 我的AJAX调用发送一个FormData对象,其中包含一个上传的图像数据:

$(document).on('submit', '#profileImageForm', function(e){
    e.preventDefault();
    var form_data = new FormData();
    var image = document.getElementById('id_banner_image').files[0].name;
    form_data.append('file', image);

    $.ajax({
        type:'POST',
        url: '/change_banner_image/',
        data : {
            form_data: form_data,
            csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
        },
        traditional: true,
        cache: false,
        success: function(response){
            console.log('Success');
        },
    });
});

and I succesfully receive the call in my views: 并且在我的视图中成功接收到该呼叫:

def change_banner_image(request):
    if request.is_ajax():
        data = request.POST.get('form_data')
        profile = get_object_or_404(Profile, user=request.user)
        profile.image = data
        profile.save()
        print(data)

    return HttpResponse()

print(data) prints: [object FormData] . print(data)打印: [object FormData] So how would I get the uploaded image from this FormData object? 那么如何从这个FormData对象获取上传的图像? Which will then be the value of profile.image (which is a FileField ). 然后它将是profile.image的值(这是一个FileField )。

The issue is because you're encoding the FormData itself, which is incorrect. 问题是因为您正在编码FormData本身,这是不正确的。 It is binary data which cannot be encoded in the manner you're attempting. 它是二进制数据,无法按照您尝试的方式进行编码。

You instead need to invert the logic to add the CSRF token to the FormData you send. 相反,您需要反转逻辑以将CSRF令牌添加到您发送的FormData You also need to set processData and contentType to false so the binary data is not amended before the request is sent, and also remove the traditional property. 您还需要将processDatacontentType设置为false以便在发送请求之前不修改二进制数据,并删除traditional属性。 Try this: 尝试这个:

$(document).on('submit', '#profileImageForm', function(e){
    e.preventDefault();
    var form_data = new FormData();
    var image = document.getElementById('id_banner_image').files[0].name;
    form_data.append('file', image);
    form_data.append('csrfmiddlewaretoken', $("input[name='csrfmiddlewaretoken']").val());

    $.ajax({
        type:'POST',
        url: '/change_banner_image/',
        data: form_data,
        processData: false,
        contentType: false,
        cache: false,
        success: function(response){
            console.log('Success');
        },
    });
});

you can try this 你可以试试这个

data = request.data

if you sending file data 如果您发送文件数据

files = request.FILES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM