前端部分
<html>
<head>
</head>
<body>
<input id="f" class="" type="file" name="file" onchange="upFile()">
</body>
<script>
var upFile = function () {
var file = document.getElementById('f');
var f = file.files[0];
//alert(f.name);
var totalSize = f.size;
var len = 2 * 1024 * 1024;
var tota_temp = Math.ceil(totalSize / len);
var start = 0;
var end = start + len;
var index = 1;
var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
var fileReader = new FileReader();
function sliceandpost()
{
if (start >= totalSize)return;
//if (index >= tota_temp)return;
var temp = f.slice(start, end);
var formData = new FormData();
formData.append('file', temp);
formData.append('fileName', f.name);
formData.append('index', index);
formData.append('start', start);
formData.append('end', end);
formData.append('totalSize', totalSize);
formData.append('tota_temp', tota_temp);
var url = '{:url('Index/uploadfile')}';
xhr = new XMLHttpRequest();
xhr.onreadystatechange=onchange;
xhr.open('POST', url);
xhr.send(formData);
function onchange()
{
// 4 = "loaded"
if(xhr.readyState==4){
// 200 = "OK"
if(xhr.status==200){
//var headers = JSON.parse(xhr.responseText);
var headers = JSON.parse(xhr.response);
console.log(headers);
//分片上传成功
if(headers.temp==0){
index = index + 1;
// 改变下一次截取的位置
start = end;
end = start + len;
// 因为截取可能超过totalSize,判断最后一次截取是否大于totalSize如果大于就直接让end等于totalSize
if (end > totalSize) {
end = totalSize;
}
sliceandpost();
}
}else{
alert("Problem retrieving XML data:" + xhr.statusText);
}
}
}
}
sliceandpost();
}
</script>
</html>
后端部分php
$myfile=$_FILES['file'];
$tmp=$myfile['tmp_name'];
$name = $_POST['fileName'];
$index = $_POST['index'];
$tota_temp = $_POST['tota_temp'];
$start = $_POST['start'];
$end = $_POST['end'];
//上传全都接收过来了,但是没用完,调试时候用的
$a='uploads/'.$index;
$path=ROOT_PATH .'public/'.$a ;
$data['f_video']=$a;
//移动临时文件到指定目录,并判断有没有成功。
if(!move_uploaded_file($tmp,$path)){
$json['src'] = $myfile;
echo json_encode($json);
} else{
//合并文件file_put_contents,file_get_contents两个函数
file_put_contents(ROOT_PATH .'public/uploads/'.$name,file_get_contents($path),FILE_APPEND);
unlink($path);//删除合并过的文件
$json['temp'] = 0;
$json['tmp'] = $tmp;
echo json_encode($json,true);
}