I created a simple file upload to my server using JavaScript.
And it works, but with some jpeg/png files I receive empty $_FILES and $_POST vars.
I tried a lot of ways, but have not found a solution.
My HTML is something like this:
<input type="file" name="fileUpload" id="fileUpload" multiple="true" onchange="upload(this.files,0);">
JS function:
upload = function(files,aid){
$.each(files,function(i,file){
if(file.type.match(/image.jpeg/) || file.type.match(/image.png/) ){
if(file.size < 10*1024*1024){
var intreval = setInterval(function(){
if(xhrCheck == false){
xhrCheck = true;
var formData = new FormData();
formData.append("file",file);
formData.append("aid",aid);
function success(data){console.log("success!");};
setTimeout(function(){
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
if (percentComplete === 100) {
xhrCheck = false;
clearInterval(intreval);
}
}
}, false);
return xhr;
},
type : "POST",
url : "/photo_uploader.php",
data : formData,
dataType : "JSON",
cache: false,
contentType: false,
processData: false,
success : success,
})
},1000);
}
},1);
}
else {
alert("more than 10mb!");
}
}
else {
alert("only JPEG or PNG allowed!");
}
});
};
In PHP I just simple show $_POST and $_FILES vars like this:
pinrt_r($_FILES);
print_r($_POST);
In normal way, a receive something like this:
Array
(
[file] => Array
(
[name] => _DSC0004.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phppUJNS5
[error] => 0
[size] => 5185226
)
)
Array
(
[aid] => 0
)
But when I chose some other pics (not all!) I receive this:
Array
(
)
Array
(
)
But if I modify this image (like resize), it normally uploads to server.
I tried use XMLHttpRequest
and replace Ajax request to this:
var xmlRq = new XMLHttpRequest();
xmlRq.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total; percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
if (percentComplete === 100) {
xhrCheck = false;
clearInterval(intreval);
}
}
}, false);
xmlRq.onreadystatechange = function () {
if (this.readyState == 4) {
if(this.status == 200) {
console.log(this.response);
}
}
};
xmlRq.open('POST', '/photo_uploader.php');
console.log(formData.getAll('file'));
xmlRq.send(formData);
With this code i have the same problem.
In FireBug i can see POST data, it's always have data to send.
I can't understand why sometimes i receive empty $_FILES and $_POST and where my mistake.
Thanks for your time and help.
/image\.jpeg/