一、jquery
<input type="file" id="file" /> <progress id="pro" value="0"></progress> <span id="output" style="font-size: 15px">等待</span><br> <button type="button" id="upload" class="btn btn-primary">上傳資源</button><br /> <input type="hidden" id="path" />
//記錄文件上傳狀態,若是文件上傳完成則爲false 不然爲true var upType = false; var page = { init: function () { $("#upload").click($.proxy(this.upload, this)); }, upload: function () { var file = $("#file")[0].files[0], //文件對象 name = file.name, //文件名 size = file.size, //總大小 succeed = 0; //從新定義文件的名字,放置重複 var path = $("#path").val(); $("#path").val(path + "." + name.replace(/.+\./, "")); name = $("#path").val(); alert(name); var shardSize = 2 * 1024 * 1024, //以2MB爲一個分片 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); //當前是第幾片 var pro = document.getElementById("pro"); pro.max = shardCount; //Ajax提交 $.ajax({ url: "/Product/UpfileProductResources/" + $("#hidProductId").val(), type: "POST", data: form, async: true, //異步 processData: false, //很重要,告訴jquery不要對form進行處理 contentType: false, //很重要,指定爲false才能造成正確的Content-Type success: function () { ++succeed; pro.value = succeed; var num = (succeed / shardCount) * 100; //展現上傳的百分比 $("#output").text(num.toFixed(2) + "%"); if (succeed == shardCount) { upType = true; } } }); } } }; $(function () { page.init(); });
二、ajax
/// <summary> /// 上傳產品資源 /// </summary> /// <param name="id">產品Id</param> /// <returns></returns> [HttpPost] public ActionResult UpfileProductResources(string id) { //從Request中取參數,注意上傳的文件在Requst.Files中 string name = Request["name"]; int total = Convert.ToInt32(Request["total"]); int index = Convert.ToInt32(Request["index"]); var data = Request.Files["data"]; string path = ConfigurationManager.AppSettings["UpPath"].ToString(); //產品資源 string serviceLocation = "/Upload/UploadFiles/Product/Resource/"; //保存一個分片到磁盤上 string dir = PublicLibrary.Public.Files.CreatePath(path + serviceLocation); //保存一個分片到磁盤上 // string dir = Server.MapPath("~/Upload"); string file = Path.Combine(dir, name + "_" + index); data.SaveAs(file); //若是已是最後一個分片,組合 //固然你也能夠用其它方法好比接收每一個分片時直接寫到最終文件的相應位置上,但要控制好併發防止文件鎖衝突 if (index == total) { file = Path.Combine(dir, name); var fs = new FileStream(file, FileMode.Create); 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); } fs.Close(); } //返回是否成功,此處作了簡化處理 return Json(new { Error = 0 }); // return json; }