关键点在后台,通过task数组来存储每个上传文件的处理任务 Task[] tasks = new Task[len]; ,然后使用 Task.WaitAll(tasks); 等待所有上传任务的完成,这里特别注意了这里必须等待,不然会丢失上传文件流(多次测试结果):
ajax上传进度效果上传 [HttpPost] 6 public JsonResult AjaxFileUp03() 7 { }; { ); (files == ; return Json(data); } allowType = , }; 17 if (files.Any(b => !allowType.Contains(b.ContentType))) 18 { ,; 20 return Json(data); 21 } (files.Sum(b => b.Length) >= 1024 * 1024 * 4) 25 { ; return Json(data); 27 } listBar = new List<MoBar>(); 31 files.ToList().ForEach(b => 32 { 33 listBar.Add(new MoBar 34 { 35 FileName = b.FileName, 36 Status = 1, 37 CurrBar = 0, 38 TotalBar = b.Length 39 }); 40 }); 41 _cache.Set<List<MoBar>>(cacheKey03, listBar); len = files.Count(); 44 Task[] tasks = new Task[len]; (int i = 0; i < len; i++) 47 { 48 var file = files.Skip(i).Take(1).SingleOrDefault(); 49 tasks[i] = Task.Factory.StartNew((p) => 50 { 51 var item = p as IFormFile; totalSize = item.Length; readSize = 1024L; [totalSize > readSize ? readSize : totalSize]; currentSize = 0L; fileName = item.FileName; , fileName); 63 using (var stream = System.IO.File.Create(path)) 64 { (var inputStream = item.OpenReadStream()) 67 { (inputStream.Read(bt, 0, bt.Length) > 0) 70 { currentSize += bt.Length; stream.Write(bt, 0, bt.Length); readSize = currentSize + readSize <= totalSize ? 80 readSize : 81 totalSize - currentSize; bt = new byte[readSize]; bars = _cache.Get<List<MoBar>>(cacheKey03); 87 var currBar = bars.Where(b => b.FileName == fileName).SingleOrDefault(); 88 currBar.CurrBar = currentSize; 89 currBar.Status = currentSize >= totalSize ? 2 : 1; 90 _cache.Set<List<MoBar>>(cacheKey03, bars); 91 92 System.Threading.Thread.Sleep(1000 * 1); 93 } 94 } 95 } 96 97 }, file); 98 } Task.WaitAll(tasks); ; 104 data.Status = 2; 105 } 106 catch (Exception ex) 107 { 108 data.Msg = ex.Message; 109 } 110 return Json(data); 111 }
至于获取上传进度的Action也仅仅只是读取缓存数据而已: