Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});
like image 386
Lancelot Avatar asked Nov 18 '25 16:11

Lancelot


1 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>
  • Using FormData
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);
  • Using File API
var reader = new FileReader();

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

reader.readAsBinaryString(file);
like image 67
Florian F. Avatar answered Nov 20 '25 05:11

Florian F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!