简体   繁体   中英

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:

$(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] . So how would I get the uploaded image from this FormData object? Which will then be the value of profile.image (which is a FileField ).

The issue is because you're encoding the FormData itself, which is incorrect. 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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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