var userInfo = {userId:"kazaff", md5:""}; //用户会话信息 var chunkSize = 5000 * 1024; //分块大小 var uniqueFileName = null; //文件唯一标识符 var md5Mark = null; var backEndUrl = "{:U('File/shard_upload',array('type'=>1,'session_id'=>session_id()))}"; WebUploader.Uploader.register({ "before-send-file" : "beforeSendFile", "before-send" : "beforeSend", "after-send-file" : "afterSendFile" }, { beforeSendFile: function(file){ //秒传验证 if (file['source']['ext'] === 'zip' || file['source']['ext'] === 'rar') { var task = new $.Deferred(); var start = new Date().getTime(); (new WebUploader.Uploader()).md5File(file, 0, 10*1024*1024).progress(function(percentage){ //console.log(percentage); }).then(function(val){ //console.log("总耗时: "+((new Date().getTime()) - start)/1000); md5Mark = val; userInfo.md5 = val; $.ajax({ type: "POST" , url: backEndUrl , data: {status: "md5Check", md5: val} , cache: false , timeout: 1000 //todo 超时的话,只能认为该文件不曾上传过 , dataType: "json" }).then(function(data, textStatus, jqXHR){ alert(data.chunk); //console.log(data); if(data.ifExist){ //若存在,这返回失败给WebUploader,表明该文件不需要上传 task.reject(); uploader.skipFile(file); file.path = data.path; }else{ task.resolve(); //拿到上传文件的唯一名称,用于断点续传 uniqueFileName = md5(''+userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size); } }, function(jqXHR, textStatus, errorThrown){ //任何形式的验证失败,都触发重新上传 task.resolve(); //拿到上传文件的唯一名称,用于断点续传 uniqueFileName = md5(''+userInfo.userId+file.name+file.type+file.lastModifiedDate+file.size); }); }); return $.when(task); } } , beforeSend: function(block){ //分片验证是否已传过,用于断点续传 if (block['file']['source']['ext'] === 'zip' || block['file']['source']['ext'] === 'rar') { var task = new $.Deferred(); $.ajax({ type: "POST" , url: backEndUrl , data: { status: "chunkCheck" , name: uniqueFileName , chunkIndex: block.chunk , size: block.end - block.start } , cache: false , timeout: 1000 //todo 超时的话,只能认为该分片未上传过 , dataType: "json" }).then(function(data, textStatus, jqXHR){ if(data.ifExist){ //若存在,返回失败给WebUploader,表明该分块不需要上传 task.reject(); }else{ task.resolve(); } }, function(jqXHR, textStatus, errorThrown){ //任何形式的验证失败,都触发重新上传 task.resolve(); }); return $.when(task); } } , afterSendFile: function(file){ if (file['source']['ext'] === 'zip' || file['source']['ext'] === 'rar') { var chunksTotal = 0; if((chunksTotal = Math.ceil(file.size/chunkSize)) > 1){ //合并请求 var task = new $.Deferred(); $.ajax({ type: "POST" , url: backEndUrl , data: { status: "chunksMerge" , name: uniqueFileName , chunks: chunksTotal , ext: file.ext , md5: md5Mark } , cache: false , dataType: "json" }).then(function(data, textStatus, jqXHR){ //todo 检查响应是否正常 task.resolve(); file.path = data.path; $("#file_name").val(data.name); $("#file_url").val(data.path+'/'+data.name); $("#file_size").val(file.size); }, function(jqXHR, textStatus, errorThrown){ task.reject(); }); return $.when(task); }else{ //UploadComlate(file); } } } });