3

I am implementing Jasny File Input plugin. However, I can't get it upload to server.

HTML

<form method="post" id="formCreateMod" class="form form-horizontal" enctype="multipart/form-data" role="form">
    <div class="fileinput fileinput-new" data-provides="fileinput">
         <div class="fileinput-preview thumbnail" data-trigger="fileinput"></div>
         <div>
              <span class="btn btn-default btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="img"></span>
              <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Delete</a>
         </div>
    </div>
</form>

The above snippet is inside the <form> tag. Then I use post in jQuery to send the serialized data of the form to server.

I am expecting to get the content in php by using $_FILES['img']["name"] or $_FILES['img']["type"], but the result is NULL.

So how should I retrieve the image data in php after the image is being posted?

Any help will be appreciated!

Update

The following is how I post the form in jQuery.

var theForm = $('form');
$.post(location.href, theForm.serialize(), function(data) {
    // handle return data
});
Lancelot
  • 1,421
  • 2
  • 17
  • 27
  • Can you post your `
    ` tag in your code as well ? (Yes, it is important)
    – Florian F. Jan 27 '14 at 12:26
  • @FlorianF. I don't quite get what you mean by post
    tag. What I am currently posting is shown in the above under Update. Is that what you mean? Or is your way different?
    – Lancelot Jan 27 '14 at 20:51
  • @FlorianF. Sorry I didn't read it closely that you want me to post the `
    ` snippet. Not like post it to jquery. (Too much things) The `
    ` snippet is now updated above. Any clue?
    – Lancelot Jan 29 '14 at 00:52

1 Answers1

7

You can't post a file using ajax and form serialization.

You should check this answer which explains why.

However, you still have solutions :

  • Not using ajax and just submitting the form using enctype='multipart/form-data' attribute on the form
<form [...] enctype='multipart/form-data'></form>
var formData = new FormData();

// HTML file input user's choice...
formData.append("userfile", fileInputElement.files[0]);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
var reader = new FileReader();

reader.onload = function(e) {
  var rawData = reader.result;
}

reader.readAsBinaryString(file);
Community
  • 1
  • 1
Florian F.
  • 4,700
  • 26
  • 50