I'm attempting to use XMLHttpRequest to upload a file, but I can't get the progress callback (req.upload.onprogress below) to work correctly. It always reports that evt.lengthComputable is false. However, the server php reports the file attributes correctly (see the log.txt listing below), and the file is correctly saved to the files directory.
Does the callback not know about the content length? If so, javascript disallows setting it, so my follow-up question would be how to set that in js ...
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Test</title>
</head>
<body>
<p>Click to select a file</p>
<form method="post" action="" id="test_form" role="form"
enctype="multipart/form-data">
<input type="file" id="test_file" required><br/><br/>
<button type="submit" id="test_button">Upload</button>
</form>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function()
{
$("#test_form").on('submit', function(evt)
{
var fileElement = $('#test_file');
var formData = new FormData();
formData.append("file", fileElement[0].files[0]);
var req = new XMLHttpRequest();
req.open("POST", document.URL);
req.upload.onprogress = function (evt)
{
if (evt.lengthComputable)
{
console.log("loaded " + evt.loaded + " total " + evt.total);
}
else
{
console.log("progress not computable");
}
}
req.send(formData);
});
});
</script>
</body>
</html>
<?php
$log_path = "log.txt";
file_put_contents($log_path, "_FILES:\n" . print_r($_FILES, true) . "\n");
foreach ($_FILES as $key => $file)
{
$src_path = $file["tmp_name"];
$dst_path = "./files/" . $file["name"];
file_put_contents($log_path, "save $src_path to $dst_path\n",
FILE_APPEND);
rename($src_path, $dst_path);
}
?>
The server reports this in log.txt:
_FILES:
Array
(
[file] => Array
(
[name] => 10.m4v
[type] => video/mp4
[tmp_name] => /tmp/phpkooBwd
[error] => 0
[size] => 3297694
)
)