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");
}
}
__EOF__

本文作者:程序员不帅哥
本文链接:https://www.cnblogs.com/Mr-Worlf/p/8709189.html
关于博主:一个精通抄代码的老猿
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/Mr-Worlf/p/8709189.html
关于博主:一个精通抄代码的老猿
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
更多精彩内容,请关注我的V信公众号:程序员不帅哥
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构