<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS分片上传-极速上传</title> </head> <body> <input type="file" name="slice" id="slice" > <a href="javascript:void(0);" onclick="sendForm()">Js File Upload!</a> <div id="output"><!-- 信息存放地 --> </div> <br/> </body> <script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $("#slice").change(function(event) { var file = $("#slice")[0].files[0]; PostFile(file,0); }); //执行分片上传 function PostFile(file,i){ var name = file.name, //文件名 size = file.size, //总大小shardSize = 2 * 1024 * 1024, shardSize = 10 * 1024 * 1024, //以2MB为一个分片,每个分片的大小 shardCount = Math.ceil(size / shardSize); //总片数 if(i >= shardCount){ return; } //console.log(size,i+1,shardSize); //文件总大小,第一次,分片大小// var start = i * shardSize; var end = start + shardSize; var packet = file.slice(start, end); //将文件进行切片 /* 构建form表单进行提交 */ var form = new FormData(); form.append("fileId", '001') form.append("data", packet); //slice方法用于切出文件的一部分 // form.append("lastModified", file.lastModified); //最后的额修改时间 form.append("name", name); form.append("totalSize", size); if(shardCount === i+1){ shardSize = size - i * shardSize } form.append("shardSize", shardSize); form.append("total", shardCount); //总片数 form.append("index", i + 1); //当前是第几片 $.ajax({ header: { web_token: "cpBvqWrr0UK9zPJoKj+412alxxcY6qFwrSVoO0juZg0S1jX/sGfMd9oi3AsSxW+MdWFrwtGCykUTmMqrqpbCElmT75DfB87lENC7lCuMxgF0d5wQB6yAubUVyGOzhbrScvIfD8ZSjOJ3D88AOy2xRd4oG8TxeGoMoZqnqIwjKg=" }, url: "http://127.0.0.1:9091/web/tool/insert_big_file", type: "POST", data: form, //timeout:"10000", //超时10秒 async: true, //异步 dataType:"json", processData: false, //很重要,告诉jquery不要对form进行处理 contentType: false, //很重要,指定为false才能形成正确的Content-Type success: function (msg) { console.log(msg); /* 表示上一块文件上传成功,继续下一次 */ if (msg.data.status == 201) { form = ''; i++; PostFile(file, i); } else if (msg.data.status == 502) { form = ''; /* 失败后,每2秒继续传一次分片文件 */ setInterval(function () { PostFile(file, i) }, 2000); } else if (msg.data.status == 200) { console.log("上传成功"); } else if (msg.data.status == 500) { console.log('第'+msg.i+'次,上传文件有误!'); } else { console.log('未知错误'); } } }) } </script> </html>
参考文章:http://blog.ncmem.com/wordpress/2023/10/08/js%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e5%88%86%e7%89%87%e4%b8%8a%e4%bc%a0/
欢迎入群一起讨论
标签:form,shardSize,js,file,分片,msg,上传,append From: https://www.cnblogs.com/songsu/p/17748551.html