//用viewModel為了通用 不同的class //此處viewModel 可能包含HttpPostFileBase物件 public void CreateViewModelToDatabase(AttachViewModel viewModel) { SaveHttpPostFile(viewModel, "~/UploadFiles"); if (viewModel.AttachDetails != null) { foreach (var item in viewModel.AttachDetails) { Create(item); if (item.AttachmentUse == "通聯記錄") { CommunRecordService srv = new CommunRecordService(); srv.Import(item); } if (item.AttachmentUse == "Cellebrite UFED報告檔") { ForensicService srv = new ForensicService(); srv.Import(item); } } } }
//將上傳的檔案,存到資料庫 public string CreateViewModelToDatabase(AttachViewModel viewModel) { SaveHttpPostFile(viewModel, "~/UploadFiles"); string errStr = String.Empty; try { if (viewModel.AttachDetails != null) { //計算excel檔案大小,用來回傳signalR CalculateFileSize(viewModel.AttachDetails); HttpContext hctx = HttpContext.Current;//使用非同步處理 httpContext.current = null //使用task非同步處理 var task = Task.Factory.StartNew(() => { foreach (var item in viewModel.AttachDetails) { Create(item); //無相關資料表 FileHelper.FileName = item.AttachmentName; if (item.AttachmentUse == "通聯記錄") { CommunRecordService srv = new CommunRecordService(); srv.Import(item, hctx); /// test //總筆數及目前處理筆數 //FileHelper.Total = 3000; ////使用Task進行非同步處理 //Random rnd = new Random(); //for (var i = 0; i < 3000; i++) //{ // //假裝將資料寫入資料庫,Delay 0-4ms // Thread.Sleep(rnd.Next(5)); // FileHelper.Count++; //} } if (item.AttachmentUse == "Cellebrite UFED報告檔") { ForensicService srv = new ForensicService(); srv.Import(item, hctx); } } }); float ratio = 0; Action updateProgress = () => { if (FileHelper.Total != 0) { ratio = (float)FileHelper.Count / FileHelper.Total; UploaderHub.UpdateProgress(viewModel.ConnId, FileHelper.FileName, ratio * 100, string.Format("{0:n0} /{1:n0}", FileHelper.Count, FileHelper.Total)); } }; while (!task.IsCompleted && !task.IsCanceled && !task.IsFaulted) { updateProgress(); Thread.Sleep(200);//0.2秒傳一次 } updateProgress(); if (task.IsCompleted && !task.IsFaulted) { return("OK"); } else { return(string.Join(" | ", task.Exception.InnerExceptions.Select(o => o.Message).ToArray())); } } } catch (Exception err) { errStr = err.Message; } UploaderHub.UpdateProgress(viewModel.ConnId, "-", 0, "-"); return(errStr); }