文件分块上传

参考:
https://blog.csdn.net/susuzhe123/article/details/73743509
https://www.cnblogs.com/baiyunchen/p/5383507.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方法,分块上传了文件

文件分块上传_第1张图片


然后,上传完毕后前台调用 Merge方法合并文件

文件分块上传_第2张图片

转载于:https://www.cnblogs.com/hanjun0612/p/9779724.html

你可能感兴趣的:(文件分块上传)