js分片上传大文件,前端代码
首先导入jQuery.form.js文件,下面src是相对于改js文件位置,
<script type="text/JavaScript" src="jquery/jquery-form.js"></script>
<script type="text/javascript">
var BYTES_PER_CHUNK = 1024 * 1024; // 每个文件切片大小定为1MB .
var slices;
var totalSlices;
//发送请求
function sendRequest() {
var blob = document.getElementById("file").files[0];
var start = 0;
var end;
var index = 0;
// 计算文件切片总数
slices = Math.ceil(blob.size / BYTES_PER_CHUNK);
totalSlices= slices;
while(start < blob.size) {
end = start + BYTES_PER_CHUNK;
if(end > blob.size) {
end = blob.size;
}
uploadFile(blob, index, start, end);
start = end;
index++;
if ( index>=totalSlices )
location="reboot.htm";
}
}
//上传文件
function uploadFile(blob, index, start, end) {
var xhr;
var fd;
var chunk;
var sliceIndex=blob.name+index;
chunk =blob.slice(start,end);//切割文件
fd = new FormData();
fd.append("UpgradeFileName", chunk, sliceIndex);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'cmd.cgi?cmd_tag=firmware_upgrade&group_tag=upgrade', false);//false指同步上传,因为我的服务器内存较小,选择同步,如果追求速度,可以选择
//ture,异步上传
xhr.send(fd);
if((xhr.status >=200 && xhr.status < 300) || xhr.status == 304){
setTimeout("",10);
}else{
uploadFile(blob, index, start, end);
}
}
</script>