HTML5大檔案分片上傳
varpage={
init:function() {
$("#upload").click($.proxy(this.upload,this));
$("#download").click($.proxy(this.download,this));
},
upload:function() {varfile=$("#file")[0].files[0],//檔案對象
name=file.name,//檔案名
size=file.size,//總大小
succeed= 0,
spark= newSparkMD5();//計算檔案的MD5值varshardSize= 2 * 1024 * 1024,//以2MB為一個分片
shardCount=Math.ceil(size/shardSize);//總片數
varcheckJson={};//接口需要
checkJson.plat={};
checkJson.data={};
checkJson.data.filename=name;
checkJson.data.filesize=size;
checkJson.data.filechunksize=shardSize;
checkJson.data.filemd5=spark.end();//檔案的MD5值
checkJson.data.creator= ‘zhanshancheng‘;varcheckJsonStr=JSON.stringify(checkJson);
console.log(shardCount);vari= 0;functionshardCountIndex (){//構造一個表單,FormData是HTML5新增的
varfileForm= newFormData();//計算每一片的起始與結束位置
varstart=i*shardSize,
end=Math.min(size, start+shardSize);//Ajax送出
$.ajax({
url:"http://10.35.1.95:18000/check_upload",
type:"POST",
cache:false,
data: checkJsonStr,
async:true,//異步
processData:false,//很重要,告訴jquery不要對form進行處理
contentType:false,//很重要,指定為false才能形成正确的Content-Type
success:function(date1) {
console.log(date1);fileForm.append("jsonData",‘{"plat":"{}","data":{"_id":"‘+date1.data._id+‘","curpos":"‘+end+‘"}}‘)
fileForm.append("data", file.slice(date1.data.curpos, end));//slice方法用于切出檔案的一部分
if(date1.success){
$.ajax({
url:"http://10.35.1.95:18000/upload",
type:"POST",
cache:false,
data: fileForm,
async:true,//異步
processData:false,//很重要,告訴jquery不要對form進行處理
contentType:false,//很重要,指定為false才能形成正确的Content-Type
success:function(date2) {++succeed;
$("#output").text(succeed+ "/" +shardCount);
console.log(date2);
if(i
shardCountIndex();
i++;
}else{return;
}
}
});
}
}
});
}
shardCountIndex();
},
download:function(){
}
};
$(function() {
page.init();
});
upload
等待
download