天天看点

html5 实现大文件上传,HTML5 大文件上传示例

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