HTML5超大文件上传
HTML5超大文件上传
big-file-upload.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
header('Content-Type: text/json');
// $filename = sprintf("%s.%d_%d_%d", $_POST['filename'], $_POST['current'], $_POST['begin'], $_POST['end']);
$filename = sprintf("%s.%d", $_POST['filename'], $_POST['current']);
move_uploaded_file($_FILES['file']['tmp_name'], $filename);
if ($_POST['current'] == $_POST['count']) {
for ($i=0; $i<$_POST['count']; $i++) {
$filename_append = sprintf("%s.%d", $_POST['filename'], $i+1);
file_put_contents($_POST['filename'], file_get_contents($filename_append), FILE_APPEND);
unlink($filename_append);
}
}
// sleep(1);
echo json_encode(array('url'=>$_POST['filename'], 'tmp_url'=>$filename));
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
window.addEventListener('load', function(){
if (window.navigator.userAgent.indexOf('Chrome') == -1) {
alert('本上传只支持谷歌浏览器!');
return;
}
document.getElementById('file').addEventListener('change', function() {
for (var i=0; i<this.files.length; i++) {
var file = this.files[i];
var block_size = 4096;
var block_count = parseInt((file.size + block_size - 1) / block_size);
for (var j=0; j<block_count; j++) {
var begin = j * block_size;
var end = j * block_size + block_size;
var block = file.slice(begin, end);
var formData = new FormData();
formData.append('count', block_count);
formData.append('current', j+1);
formData.append('begin', begin);
formData.append('end', end);
formData.append("filename", file.name);
formData.append("file", block);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'big-file-upload.php', false);
xhr.onload = function() {
if (this.status == 200) {
var response = JSON.parse(this.responseText);
if (j+1 == block_count) {
var img = new Image();
img.src = response.url;
document.body.appendChild(img);
alert('上传完成!');
} else {
var span = document.createElement('p');
span.innerHTML = response.tmp_url;
document.body.appendChild(span);
}
} else {
alert('error: '+this.status);
}
};
xhr.send(formData);
}
}
});
});
</script>
</head>
<body>
<input type="file" id="file" multiple="multiple" /><br />
</body>
</html>