I am trying to build an AJAX image upload using FormData() and it is not working for Firefox and IE. In Chrome everything behaves well; the php script receives form-data object and returns response as expected.
However, in Firefox and Internet Explorer an empty string is always returned as a response (the AJAX call is successfully sent). When I check in the plain Network tab, the size of content is 0. When I check this in Firebug's Network tab, POST tab it actually says that my FormData() contains the file:
Content-Disposition: form-data; name="fileToUpload"; filename="9VMyIQM4Vg8.jpg" Content-Type: image/jpeg
But content-length is 0 and php script cannot retrieve the file. Even if I try creating FormData() manually with append, it doesn't help.
Firefox version 35.0.1 (and docs say the FormData() should work just fine) and IE version 11 (so it's supposed to handle FormData() too). Any help will be very much appreciated!
Here is my code (I shortened php script for testing).
HTML:
<form method="post" action='upload.php' name='imageUploadForm' id="imageUploadForm" enctype="multipart/form-data">
<div class="form-group">
<label for='fileToUpload'>Select image to upload:</label>
<input type="file" name="fileToUpload" id="fileToUpload" />
<button type="submit" name="uploadBtn" id="uploadBtn">Preview image</button>
<p id='uploadResult'></p>
</div>
</form>
JQuery:
$('#imageUploadForm').on('submit', function (event) {
var form = $(this);
event.preventDefault();
var formData = false;
if (window.FormData) {
formData = new FormData(form[0]);
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("success");
console.log(data);
$('#uploadResult').text(data);
},
error: function (data) {
console.log("error");
console.log(data);
$('#uploadResult').text(data);
}
});
});
PHP:
if ($_POST) {
if (!empty($_FILES['fileToUpload']['name'])) {
$image = basename($_FILES['fileToUpload']['name']);
$target_file = $target_dir . $userID . "_" . basename($_FILES["fileToUpload"]["name"]);
echo $target_file;
} else {
print 'Please select a file to upload.';
}}
Even if I try to send empty form, I don't get the error "Please select the file to upload".