Ajax 文件切割上传
2017-02-24 09:56 归属感 阅读(274) 评论(0) 收藏 举报<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
#progress{
width: 500px;
height: 30px;
border: 1px solid green;
}
#bar{
width: 0%;
height: 100%;
background: green;
}
</style>
<!--
用到的Api
file->继承自->Blob
Blod对象有slic方法,可以截取二进制的一部分,能做大文件上传的理论基础
思路:
截取10M ,上传
判断文件有没有截取完毕
用定时器,不断使用用上传方法
-->
<body>
<h1>视频分割上传</h1>
<div id="progress">
<div id="bar"></div>
</div>
<input type="file" name="mov" onchange="fire()">
<div id="debug"></div>
</body>
</html>
<script src="../../jquery-1.7.js"></script>
<script>
var xhr = new XMLHttpRequest(); //XMLHttpRequest 对象用于在后台与服务器交换数据。
var clock = null; //先定义一个时间空值
function fire(){
clock = window.setInterval(sendfile,1000); //每隔一秒钟 调用一次
}
// 闭包计数器
var sendfile = (function(){
// 生成一个固定截取的长度
const LENGTH = 10 * 1024 * 1024; //用字节 长度位10M 每次切10M
var sta = 0; //开始截取的位置
var end = sta + LENGTH; //结束的位置
var sending = false; //标志正在上传中
var blob = null; //一个截取的空值
var fd = null; //FormData 为空值
var percent = 0;
return (function (){
if(sending == true){
return;
}
var mov = document.getElementsByName('mov')[0].files[0];//console.log(mov);return false;//获取文件
//如果sta > mov.size,就结束了
if(sta > mov.size){
clearInterval(clock); //清除一下闭包计数器
return;
}
blob = mov.slice(sta,end); //截取;
fd = new FormData();
fd.append('part',blob);
up(fd); //调用函数
sta = end; //重新赋值 开始值
end = sta + LENGTH; //重新赋值 结束值
sending = false; //上传完成 改为true
percent = 100 * (end / mov.size); //百分比 上传的文件与 总值的百分比
if(percent>100){
percent = 100;
}
document.getElementById('bar').style.width = percent + '%'; //进度条
});
})();
function up(fd){
xhr.open('POST','./sliceup.php',false);
xhr.send(fd);
}
</script>


后台操作
<?php
/*
接收文件并合并
*/
if(!file_exists('./upload/up.wmv')){
move_uploaded_file($_FILES['part']['tmp_name'],'./upload/up.wmv');
}else{
file_put_contents("./upload/up.wmv",file_get_contents($_FILES['part']['tmp_name']),FILE_APPEND);
}
// echo "ok";
?>

浙公网安备 33010602011771号