Peyman Kheiri
Peyman Kheiri

Reputation: 427

Sending image file via AJAX. request.FILES is empty?

I am trying to send image data using Ajax. But request.FILES that I get at the backend is empty. I have added multipart/form-data to my form and the method is POST.

here is my AJAX call:

 $(document).on('submit', '#profile_edit_form', function(event){

  event.preventDefault();


  $.ajax({
      url     : "/users/update_profile_info/",
      type    : 'post',
      dataType: 'json',
      data    : $(this).serialize(),
      success : function(data) {

        $('#profile_name_tag').html(data.username);
        $('#username_navbar').html(data.username);

        //SENDING THE IMAGE VIA AJAX HERE
        var img_data = $('#id_image').get(0).files;
        formdata = new FormData();
        formdata.append("img_data", img_data);

        $.ajax({
            url         : "/users/update_profile_image/",
            type        : 'POST',
            enctype     : "multipart/form-data",
            data        : formdata,
            cache       : false,
            contentType : false,
            processData : false,
            success : function(data) {
              console.log('success');
              //$('#profile_picture').html(data.)

            },
            error: function(data) {
              console.log('fail');
            }
        });

      },
      error: function(data) {
          console.log('fail');
      }
  });


});

and here is my form:

   <form id="profile_edit_form" method="POST">
     {% csrf_token %}
     <fieldset class="form-group">
       <legend class="border-bottom mb4"> Profile Info </legend>
             {{u_form|crispy}}
            {{p_form|crispy}}
     </fieldset>
     <button class="btn btn-outline-info" type="submit"> Update Info </button>
   </form>

As you can see I am using cispy forms. the image field is inside the p_form

and here is my django view

@login_required
def update_profile_image(request):
    print(not request.FILES)

    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user)
        if p_form.is_valid():
            p_form.save()

            context = {'None': 'none'}
            return JsonResponse(context)
        else:
            return HttpResponse('None')

print(not request.FILES) returns True and the image is of course not uploaded.

I have checked so many similar questions. but in all of them the solution was adding multipart/form-data to the form which I have already done. So any ideas where the problem is?

thanks!

Upvotes: 2

Views: 2818

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You're providing the entire files collection to FormData.append(), when it expects a single entity.

Try just accessing the single file from files and passing that instead:

var img_data = $('#id_image').get(0).files[0]; // note [0]

I would also suggest removing the enctype settings, as jQuery will do this for you automatically when you provide a FormData object to the request. Manually setting the value may overwrite the setting with an incorrect value.

Upvotes: 2

Peyman Kheiri
Peyman Kheiri

Reputation: 427

I changed the code to

var img_data = $('#id_image').get(0).files[0];
formdata = new FormData();
formdata.append("img_data", img_data);
//console.log(formdata.get("img_data"));

$.ajax({
    url         : "/users/update_profile_image/",
    type        : 'POST',
    //enctype     : "multipart/form-data",   //it is done inside jquery
    data        : formdata,
    cache       : false,
    contentType : false,
    processData : false,
    success : function(data) {
      console.log('success');
      //$('#profile_picture').html(data.)

    },
    error: function(data) {
      console.log('image-fail');
    }
});

and it finally worked!

Upvotes: 2

Related Questions