I have a problem with Ajax uploading using Jquery and PHP.. Although there're many stackoverflow posts discussing the same subject, I didn't find one that matches my case.
HTML :
<form action="uploadrecord.php" id="upload_record_form" method="post" enctype="multipart/form-data">
<div id="upload_record_form_result"></div>
<ul>
<li><input type="file" name="uploadrecord" id="uploadrecord"/></li>
</ul>
<progress></progress>
</form>
</div>
Javascript :
$('#uploadrecord').live('change', function(event) {
var formData = new FormData($('#upload_record_form')[0]);
$.ajax({
url: $('#upload_record_form').attr('action'),
type: 'POST',
enctype: 'multipart/form-data',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler = function(data) {
$('#upload_record_form_result').html(data);
},
error: errorHandler = function() {
alert("Failure");
},
data: formData,
cache: false,
contentType: false,
processData: false
}, 'json');
});
PHP
<?php
if (isset($_FILES['uploadrecord'])) {
if ((!empty($_FILES["uploadrecord"])) && ($_FILES['uploadrecord']['error'] == 0)) {
$filename = basename($_FILES['uploadrecord']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
$types = array(
'video/mp4', 'video/3gpp', 'video/divx', 'video/flv', 'video/mpeg', 'video/mpeg-2', 'video/mpeg4', 'video/mpeg4'
);
$type = $_FILES['uploadrecord']['type'];
if (in_array($type, $types) && $_FILES["uploadrecord"]["size"] < 20000000) {
$new = sha1(date('Y/m/d H:i:s'));
$newname = dirname(__FILE__) . '/records/' . $new . '.' . $ext;
if ((move_uploaded_file($_FILES['uploadrecord']['tmp_name'], $newname))) {
echo 'done';
} else {
echo 'failed 1';
}
}
} else {
echo 'failed 2';
}
} else {
echo 'Upload failed 3';
}
When I try the previous code, and upload a record file, it displays "failed 2", meaning that the "error" code is different from 0.
when I var_dump the array $_FILES['uploadrecord']...this is what I get:
array (size=5)
'name' => string 'Nao Robot.flv' (length=13)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 1
'size' => int 0
I can't figure out, why 'tmp_name' and type are set to empty strings, and why the size is set to 0.
Where's the problem exactly? is it from the client or server side scripting?
Thanks in advance