0

I am facing a problem while attempting to send an image through an AJAX request to Django. Here is my HTML:

<form>
<input type="file" id="files" name="image">
</form>

Here is my JS :

var control = document.getElementById("files");
var p = {
        title: $('input[name=title]').val(),
        subtitle: $('input[name=subtitle]').val(), 
        content: $('textarea#article-content').val(),
        image: files[0],
    };
    $.ajax({
        url: '/prive/nouveau-projet',
        type: "POST",
        data: JSON.stringify(p),
        crossDomain: true,
        success: function() {
            window.location.href = '/prive/projets/';
        },
        error: function() {
            console.log("error");
        }
    });

And here is my server-side code:

if request.method == "POST":
    data = request.POST.keys()[0]
    dataJson = json.loads(data)
    p = Projet(title=dataJson['title'], subtitle=dataJson['subtitle'], content=dataJson['content'], image=dataJson['image'])
    p.save()
    return HttpResponse()

That is what I tried but I get errors about dataJson['image']. Could you help me please ?

1 Answer 1

2

you dont need JSON.stringify.

just write it like this:

var data = new FormData();
var img = $('#image_field_id')[0].files[0];
data.append('img', img);
$.ajax({
    url : "/prive/nouveau-projet",
    processData : false,
    contentType : false,
    type : 'POST',
    data : data,
}).done(function(data) {
    // work with data              
});

and in views

if request.method == "POST":
    file = request.FILES.get('img') # FILES instead of POST
    ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.