先来前端代码
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>大文件分割上传</title> <script src="~/js/jquery.min.js"></script> <script> var page = { init: function () { $("#subUpload").click($.proxy(this.upload, this)); }, upload: function () { var file = $("#fileUpload")[0].files[0], //文件对象 name = file.name, //文件名 size = file.size, //总大小 succeed = 0; var shardSize = 290 * 1024, //以290kb为一个分片,换算1MB=1 * 1024 * 1024 shardCount = Math.ceil(size / shardSize); //总片数 for (var i = 0; i < shardCount; ++i) { //计算每一片的起始与结束位置 var start = i * shardSize, end = Math.min(size, start + shardSize); //构造一个表单,FormData是HTML5新增的 var form = new FormData(); form.append("data", file.slice(start, end)); //slice方法用于切出文件的一部分 form.append("name", name); form.append("total", shardCount); //总片数 form.append("index", i + 1); //当前是第几片 //Ajax提交 $.ajax({ url: "../Upload/SaveFile2", type: "POST", data: form, async: true, //异步 processData: false, //很重要,告诉jquery不要对form进行处理 contentType: false, //很重要,指定为false才能形成正确的Content-Type success: function () { ++succeed; $("#output").text(succeed + " / " + shardCount); } }); } } }; $(function () { page.init(); }); </script> </head> <body> <div> <input id="fileUpload" name="fileUpload" type="file" /><br /> <button id="subUpload" type="submit">提交</button><br /> <span id="output" style="font-size:12px">等待</span> </div> </body> </html>再来C#版后台代码
public ActionResult SaveFile2() { string name = Request["name"]; int total = Convert.ToInt32(Request["total"]); int index = Convert.ToInt32(Request["index"]); var data = Request.Files["data"]; string dir = Server.MapPath("/UploadFile/Imgs/"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string file = Path.Combine(dir, name + "_" + index); data.SaveAs(file); string[] files = Directory.GetFiles(dir); bool isMerge = true; for (int i = 1; i <= total; ++i) { string part = Path.Combine(dir, name + "_" + i); if (!files.Contains(part)) { isMerge = false; } } if (isMerge) { file = Path.Combine(dir, name); var fs = new FileStream(file, FileMode.Create); try { for (int i = 1; i <= total; ++i) { string part = Path.Combine(dir, name + "_" + i); var bytes = System.IO.File.ReadAllBytes(part); fs.Write(bytes, 0, bytes.Length); bytes = null; System.IO.File.Delete(part); } } finally { fs.Close(); } } //返回是否成功,此处做了简化处理 return Json(new { Error = 0 }); }