I am trying to make an ajax upload function with progress bar, i was trying to simplify an example i found of the internet and i came to this function:
<form>
<input type="file" id="file" /><label for="file"></label><label id="aaa"></label>
<button id="sub">abc</button>
</form>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function uploadFile(files) {
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.upload.onprogress = function(e) {
$("#aaa").empty().append(e.loaded + " - " + e.total);
}
xmlhttp.upload.onload = function(e) {
$("#aaa").empty().append("finish");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("post", "post.php", true);
xmlhttp.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
xmlhttp.setRequestHeader("Cache-Control", "no-cache");
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlhttp.setRequestHeader("X-File-Name", files[0].fileName);
xmlhttp.setRequestHeader("X-File-Size", files[0].fileSize);
xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlhttp.send(files[0]);
}
$(document).ready(function() {
$("#file").change(function() {
uploadFile(this.files);
});
});
</script>
it is working well when i upload files near or under 800kb - 1MB and it's very fast but it bugs out when i try to upload bigger files. The progress bar shows that it's uploading but the onreadystatechange doesnt trigger and the file doesnt appear on the server.
The php which reply to this ajax is this:
<?php
// e.g. url:"page.php?upload=true" as handler property
//print_r($_SERVER);
if(
// basic checks
isset(
$_SERVER['CONTENT_TYPE'],
$_SERVER['CONTENT_LENGTH'],
$_SERVER['HTTP_X_FILE_NAME']
) &&
$_SERVER['CONTENT_TYPE'] == 'multipart/form-data'
){
// create the object and assign property
/*$file = new stdClass;
$file->name = basename($_SERVER['HTTP_X_FILE_NAME']);
$file->size = $_SERVER['HTTP_X_FILE_SIZE'];
$file->content = file_get_contents("php://input");
// if everything is ok, save the file somewhere
if(file_put_contents('files/'.$file->name, $file->content))
echo "OK";*/
$file->name = basename($_SERVER['HTTP_X_FILE_NAME']);
$input = fopen('php://input', 'rb');
$file = fopen('files/'.$file->name, 'wb');
stream_copy_to_stream($input, $file);
fclose($input);
fclose($file);
} else {
// if there is an error this will be the output instead of "OK"
echo "Error";
}
?>
Thank you in advance, Daniel!