Using Jasny file input to upload file to the server using PHP

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
});

Answers


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);

Need Your Help

Generated thumbnails are all black when uploading

php image upload thumbnails

I'm generating thumbnail images from the original jpeg files when they are being uploaded. I could actually create and move those thumbnail files to another directory, but the problem is that those

Is there a less painful way to GetBytes for a buffer not starting at 0?

c# bytearray bitconverter

I am having to deal with raw bytes in a project and I need to basically do something like this