C#实现文件异步上传
//前台方法,包含弹出框确认以及文件选择
<input type="button" id="importxlsx" name="importxlsx" class="k-button" style="line-height: 20px" value="@T("Admin.Common.ImportFromExcel")" /> <div id="importexcel-window" style="display:none;"> @using (Html.BeginForm("ImportExcel", "ProductCarrefour", FormMethod.Post, new { name = "ImportExcelForm", enctype = "multipart/form-data" })) { <table style="text-align:left;"> @*<tr> <td colspan="2"> <em>@T("Admin.Catalog.Products.List.ImportFromExcelTip")</em> </td> </tr>*@ <tr> <td> @T("Admin.Common.ZIPFile"): </td> <td> <input type="file" id="importexcelfile" name="importexcelfile" /> </td> </tr> <tr> <td colspan="2"> <strong>@T("Admin.Configuration.File.MaxLengthFor200")</strong> <br /> <strong>@T("Admin.Configuration.Languages.XmlFile.Note1")</strong> <br /> <strong>@T("Admin.Configuration.Languages.XmlFile.Note2")</strong> </td> </tr> <tr> <td colspan="2"> <input type="button" class="k-button" onclick="checkIsExcel(this)" value="@T("Carrefour.Admin.Controllers.GoodsController.ImportZIP")" /> @*<input type="submit" id="ExcelInEnsure" style="display: none" />*@ @*<input type="submit" class="k-button" value="@T("Admin.Common.ImportFromExcel")" />*@ </td> </tr> </table> } </div> <script type="text/javascript"> function checkIsExcel(v) { var ImportExcelForm = $("#ImportExcelForm"); var file = $("#importexcelfile").val(); if(file=="") { alert("請選擇文件"); return; } var strTemp = file.split("."); var strCheck = strTemp[strTemp.length-1]; if(strCheck.toUpperCase()=='ZIP'||strCheck.toUpperCase()=='zip') { //$("#ExcelInEnsure").trigger("click"); submitImportProduct(); }else { alert('上傳文件類型不對!'); return; } } function submitImportProduct() { debugger; var formData = new FormData(); formData.append("importexcelfile", $("#importexcelfile")[0].files[0]); $.ajax({ type: 'POST', url: '@Url.Action("ImportExcel", "Product")', data: formData, cache: false, contentType: false, processData: false, success: function (data) { return false; } }); $("#importexcel-window").data("kendoWindow").close(); alert("文件正在異步上傳,請在上傳記錄中查看上傳狀態。") window.open("@storeLocation" + "admin/common/UploadLogList"); return false; } </script> <script type="text/javascript"> $(document).ready(function () { $("#importexcel").click(function (e) { e.preventDefault(); var window = $("#importexcel-window"); if (!window.data("kendoWindow")) { window.kendoWindow({ modal: true, width: "400px", title: "@T("Admin.Common.ImportFromZIP")", actions: ["Close"] }); } window.data('kendoWindow').center().open(); }); }); </script>
//后台方法 [HttpPost] public ActionResult ImportExcel() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts) && !_permissionService.Authorize(StandardPermissionProvider.ManageVendorProducts)) return AccessDeniedView(); var deleteZipFile = _settingService.GetSettingByKey("productimport.deleteproductzipfile", false); string tempFileName = CommonHelper.GetDateTimeNow().ToString("yyyyMMddHHmmssfff"); var file = Request.Files["importexcelfile"]; var flagFile = Server.MapPath("~/Administration//Template//" + Path.GetFileNameWithoutExtension(file.FileName)); if (System.IO.File.Exists(flagFile)) { ErrorNotification(string.Format(_localizationService.GetResource("Admin.Catalog.Products.FileOnUploading"), file.FileName)); return RedirectToAction("List"); } FileStream myFs = new FileStream(flagFile, FileMode.Create); myFs.Close(); string filePath = Server.MapPath("~/Administration//Template//" + tempFileName + ".zip"); string backupPath = Server.MapPath("~/Administration//BackupFiles//ProductImportZipFiles//"); string dir = Server.MapPath("~/Administration//Template//" + tempFileName + ""); try { file.SaveAs(filePath); if (!Directory.Exists(Server.MapPath("~/Administration//Template//" + tempFileName + ""))) { // Create the directory it does not exist. Directory.CreateDirectory(Server.MapPath("~/Administration//Template//" + tempFileName + "")); } //如果解压缩成功 if (CopyToAndUnzipFile(filePath, tempFileName)) { DirectoryInfo dirinfo = new DirectoryInfo(Server.MapPath("~/Administration//Template//" + tempFileName + "")); var afileinfo = dirinfo.GetFiles(); List<string> excelCount = (from fi in afileinfo where Path.GetExtension(fi.Name).ToUpper() == ".XLS" || Path.GetExtension(fi.Name).ToUpper() == ".XLSX" select fi.FullName).ToList(); if (excelCount.Count == 1) //如果只存在一个excel文件 { using (FileStream fileStream = new FileStream(excelCount[0], FileMode.Open, FileAccess.Read)) { _importManager.ImportProductsFromXlsxAsync(fileStream, Server.MapPath("~/Administration//Template//" + tempFileName + ""), file.FileName, filePath, deleteZipFile, flagFile, backupPath, dir); } return RedirectToAction("List"); //} } if (excelCount.Count > 1) { ErrorNotification(_localizationService.GetResource("Admin.Catalog.Products.ImportProductAndGoodsExistOneMoreExcel")); } else if (excelCount.Count == 0) { ErrorNotification(_localizationService.GetResource("Admin.Catalog.Products.ImportProductAndGoodsExistZeroExcel")); } } return RedirectToAction("List"); } catch (Exception exc) { TempData["ErrorMsg"] = exc.Message; if (exc.InnerException != null) { string logError = string.Format("商品導入出錯,error:{0}", exc.InnerException.InnerException); _logger.InsertLog(LogLevel.Error, logError, logError); } return RedirectToAction("List"); } }
更多精彩内容,请关注我的V信公众号:程序员不帅哥