mdnba50
mdnba50

Reputation: 379

jQuery FormData and files

I'm attempting to do ajax file upload. When i check the variable form_data it is blank?

<form action='ajax_image_upload/process.php' method='post' enctype='multipart/form-data' class='upload_form'>
  <textarea name='description' placeholder='Type Default Video Description'></textarea>
  <span>
    Channel Image: <input type='file' name='image' />
  </span>  
  <input name='__submit__' type='submit' value='Upload'/>
</form>
var container = $(".upload_form");
var form_data = new FormData();    
form_data.append('image', container.find("form > span").children("input[name='image']"));

var post_url = container.children("form").attr("action"); //get action URL of form

//jQuery Ajax to Post form data
$.ajax({
  url : post_url,
  type: "POST",
  data: form_data,
  contentType: false,
  cache: false,
  processData: false,
  mimeType: "multipart/form-data"
}).done(function(res){ 
});

How can I solve this?

Upvotes: 0

Views: 290

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you need to append the binary data from the file input to the FormData, not the jQuery object. Try this:

var fileData = container.find("form > span").children("input[name='image']")[0].files[0]; 
form_data.append('image', fileData);

Obviously, if there are multiple inputs, or multiple files within the input, you'll need to loop through them and append them individually.

Upvotes: 1

Related Questions