文件分块上传
參考:
https://blog.csdn.net/susuzhe123/article/details/73743509
https://www.cnblogs.com/baiyunchen/p/5383507.html
直接上代碼:
前臺:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title><script src="../Scripts/jquery-1.8.2.js"></script> </head> <body><input type="file" id="file" /> <button id="upload">上傳</button> <span id="output">等待中</span> </body><script>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 shardSize = 4 * 1024 * 1024, //以4MB為一個分片 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: "../Test/Upload",type: "POST",data: form,async: true, //異步 processData: false, //jquery不要對form進行處理 contentType: false, //指定為false才能形成正確的Content-Type success: function () {//成功后的事件 succeed++;if (succeed == shardCount){Merge();}}});}}};function Merge() {$.ajax({url: "../Test/Merge",type: "get",success: function () {}});}$(function () {page.init(); //初始化 });</script> </html>后臺:
[HttpPost]public ActionResult Upload(){string fileName = Request["name"];int index = Convert.ToInt32(Request["index"]);//當前分塊序號var folder = "myTest";var dir = Server.MapPath("~/Images");//文件上傳目錄dir = Path.Combine(dir, folder);//臨時保存分塊的目錄if (!System.IO.Directory.Exists(dir))System.IO.Directory.CreateDirectory(dir);string filePath = Path.Combine(dir, index.ToString());var data = Request.Files["data"];//表單中取得分塊文件data.SaveAs(filePath);//保存return Json(new { erron = 0 });}public ActionResult Merge(){var folder = "myTest";var uploadDir = Server.MapPath("~/Images");//Upload 文件夾var dir = Path.Combine(uploadDir, folder);//臨時文件夾var fileName = "MyTest.jpg";//文件名var files = System.IO.Directory.GetFiles(dir);//獲得下面的所有文件var finalPath = Path.Combine(uploadDir, fileName);//最終的文件名(demo中保存的是它上傳時候的文件名,實際操作肯定不能這樣)var fs = new FileStream(finalPath, FileMode.Create);foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保證從0-N Write{var bytes = System.IO.File.ReadAllBytes(part);fs.Write(bytes, 0, bytes.Length);bytes = null;System.IO.File.Delete(part);//刪除分塊}fs.Close();System.IO.Directory.Delete(dir);//刪除文件夾return Json(new { error = 0 });//隨便返回個值,實際中根據需要返回}解釋一下:
首先,前臺ajax調用upload方法,分塊上傳了文件
然后,上傳完畢后前臺調用 Merge方法合并文件
轉載于:https://www.cnblogs.com/hanjun0612/p/9779724.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: stm32的PWM占空比
- 下一篇: android 实现微信分享多张图片的功