0

I have an html form which I am trying to upload, the form contains an image file. I submit the form and then prevent it's default through javascript, finally, I make a jquery Post (without refreshing the page) with the information the form had. Yet, the image file is not being send. Here is my html form:

<form role="form" method="post" action="/client/client/update/image/" enctype="multipart/form-data" id="form-change-image">
<input type='hidden' name='csrfmiddlewaretoken' value='EXRSJGjjq3hMYd5b71UKcpEQ7XwPSonK' />
<input accept="image/*" class="hidden" id="id_image" name="image" type="file" />
</form>

Here is the jquery:

$(document).on('submit', '#form-change-image', function(e) {
  var form;
  e.preventDefault();
  form = $(this);
  $.post(this.action, $(this).serialize()).done(function(data) {
    $('#img_client').attr('src', image_preview);
  }).fail(function(data) {
    $('#main-row #result-alert').remove();
    $('#main-row').prepend('<div id="result-alert" class="alert alert-danger alert-dismissible" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="Cerrar">' + '<span aria-hidden="true"><i class="fa fa-times"></i></span>' + '</button>' + '<strong><i class="fa fa-frown-o"></i>Lo sentimos.</strong> ' + data.responseJSON.response + '</div>');
  });
});

The csrfmiddlewaretoken is arriving as expected, the image is not appearing in the request.FILES nor the request.POST

How can I modify the post so that the image also arrives.

Oscar Vasquez
  • 465
  • 2
  • 6
  • 14
  • 2
    possible duplicate of [How can I upload files asynchronously?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – imtheman Sep 09 '15 at 21:27

1 Answers1

0

Try the following:

$(document).on('submit', '#form-change-i1mage', function(e) {

  e.preventDefault();

  $.post(this.action, new FormData(this))
      .done(function(data) {
        $('#img_client').attr('src', image_preview);
      })
      .fail(function(data) {
        $('#main-row #result-alert').remove();
        $('#main-row').prepend('<div id="result-alert" class="alert alert-danger alert-dismissible" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="Cerrar">' + '<span aria-hidden="true"><i class="fa fa-times"></i></span>' + '</button>' + '<strong><i class="fa fa-frown-o"></i>Lo sentimos.</strong> ' + data.responseJSON.response + '</div>');
      });
    });

Notice the new FormData(this) instead of $(this).serialize()

If that doesn't work use $.ajax instead of $.post so you can set the contentType option to false

JSelser
  • 3,510
  • 1
  • 19
  • 40