ASP.NET MVC 4 Ajax上传文件

时间:2023-11-24 20:28:26

这两天一直纠结着表单的问题。想在一个表单里实现三个功能:

  1. 输入查询条件,点击查询;
  2. 导出查询数据;
  3. 上传文件;

方法有很多,乱花渐欲迷人眼,尝试了很多,无果。大致说的是,给不同按钮写js代码,在js代码里设置url和get、post、multipart/form-data等属性。看到猎风的demo很不错:

 <script type="text/javascript">
function save()
{
document.form1.action="a.asp";
document.form1.submit();
} function send()
{
document.form1.action="b.asp";
document.form1.submit();
}
</script>
</head>
<body>
<form name="form1">
<input type="text" name="username" value="scott">
<input type="button" value="发送" onclick="send();">
<input type="button" value="保存" onclick="save();">
</form>
</body>

很清晰的代码!可惜我用不上。

后来终于做了一个艰难的决定——上传文件用一个form,另两个功能用一个form,总共两个form。

上传文件用MVC的html辅助方法吧:

@using (@Html.BeginForm("ImportExcel0", "BOM",  FormMethod.Post, new { id = "UploadForm", enctype = "multipart/form-data" }))
{
<input type="file" id="FileUpload1" name="FileUpload1" />
<input id="import" type="submit" value="导入Excel" />
}

哦,这个虽然可以上传文件,但是刷新页面会重复提交。好吧,用Ajax.BeginForm,这个是异步的应该不会导致重复提交。折腾许久发现这个Ajax.BeginForm根本不能上传文件!要异步上传文件,还得用jquery.form.js这个插件。http://malsup.com/jquery/form/

Let's go !

HTML:

 <form id="UploadForm" name="UploadForm" action="/BOM/ImportExcel0/" method="post" enctype="multipart/form-data">
<input type="file" id="FileUpload1" name="FileUpload1" />
<input id="import" type="submit" value="上传" />
</form>

Javascript:

  $("#UploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
if ($('#FileUpload1').val() == '') {
alert('请选择文件!');
return false;
}
},
success: function (result) {
$("#UploadForm").resetForm();
var DialogVars = $.parseJSON(result);//响应信息
if (result.success) {
toastr.success(result.message, 'Success Message')
alert(result.message);
//导入成功后记录数没实时更新
$("#list").trigger("reloadGrid");
}
else {
toastr.error(result.message, 'Error Message')
alert(result.message);
}
},
error: function (xhr, textStatus, errorThrown) {
$("#UploadForm").resetForm();
toastr.error('文档上传错误.', 'Error Message')
}
});

这里有些东西后面介绍。

Controller:

  public ActionResult ImportExcel0()
{
if (Request.Files["FileUpload1"] != null && Request.Files["FileUpload1"].ContentLength > )
{
string fileName = System.IO.Path.GetFileName(Request.Files["FileUpload1"].FileName);
//string extension = System.IO.Path.GetExtension(fileName);
string serverPath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), fileName);
if (System.IO.File.Exists(serverPath))
System.IO.File.Delete(serverPath); Request.Files["FileUpload1"].SaveAs(serverPath); try
{
ImportExportData.ImportExcel(serverPath, "BOMs");
ViewBag.Msg = "good";
System.IO.File.Delete(serverPath);
return Json(new { success = true, message = "导入成功!", fileName = fileName });
}
catch (Exception ex)
{
ViewBag.Msg = ex.Message;
System.IO.File.Delete(serverPath);
return Json(new { success = false, message = "导入失败" + ex.Message, fileName = fileName });
}
}
return View("Index");
}

看起来还行,可以运行。但是问题接踵而来。

1、在IE8里点击上传文件后,文本框内容不消失,如果继续点击上传按钮,还会上传一次。

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAATUAAAATCAIAAAB+/w3MAAAFLElEQVR4nO2bzW7bRhDHB1UPki0byDnXwm1U+9R7kHsBn1qEzkPkAXJJIcVtc8gjFELQGI6KAnkJA00NxHmAJkEqhTQpRUrctD2Uh/Qw1nQ6O7tcWSL1EQ7+IJbL4XJ3Mz/ucOXAP3/9LXT48NFoOCq17Dp8+Ij+Tb//6XRlZEZscPf96wWw4O57s29TCko+V1WCz8FZahMAqOXMGvNS3ir5LPlcEQk++2epQwCglvmpWuDmfsRMZONzMLZqtTqX42AwKPksNYEEn8nbdFIBAB0dBTotQG4+CRWHAcBEPj7+c+Yzfvfga/j83uMhr2zvVW7+cF6OTlpbABtw/ec3Q37XV/CRqLQJW+D25a3juYf4pDLnZMoR9c+Ob3/2X5t58wmGeWJZGKI2PvveBgAT+WT6V6tVLCwWn2EnoICLTloNaGztAI+ksBNUGle+gMCT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z4Hf+skTS7XnYimmx5nbrWJOHCMyn6g2aHZ4Z/dAdEPdvzX5fN5PV0BuPgmVmfApKM20pf/7Ps8f7kpNKZXPZ0m6ArLx+cppkGXCWW3B1ni9XsfC0vNp/uxZKg99gHz2er1er7exsdGbny0xn+of6JbKSSqfv8XpCsjN51yMXgpLzGep4vVB/f/sbrfb7XY3NzfnckQrjs9Sq6GZh8tiivicr+XB57/5D/c6q8iPLAAAAABJRU5ErkJggg==" alt="" />

2、在IE8里上传成功后应该返回一个信息,这个信息是json格式的,但是IE8接收不到json格式的数据!实际情况是,当点击上传按钮后,本期望的弹出信息没看到反而出来一个下载提示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmoAAABzCAIAAACn9rlSAAAXMUlEQVR4nO2dbXBU13nHjyV3DDbEkw/xC3Y6adM4CS82RNAxDMnYzNie8Qs4nRKvJGwQaZvpFzzOpw6JjdFKxsSySdsP7UwwSOLFFqI0Bgao/aUIJCQBgspt7UmcCRbSvkgrCWSMQFi9/fBon332nPu6L6zY/f/mGebq7rlnz3P27vndc+6VUBYAAAAAAqIK3QAAAADg1gP6BAAAAAKjJr68ikAUWYS2WtMnCt4bCAQiH+Gtzzf3RRHFEQU/225ahLZaI8Mj0yGgTwSiWMOXPgs+BiGyD6nP94oL86QNbbUS0wPoE4Eo1oA+SyU0fbqUVErZbnvuMV+6CeGuzzvuuKMg/0KfCETRB/RZKqHp033OpJSy3ZY/2m5I/E7QssNJn0OFY8aMGbwNfSIQxRrQZ6lEIH3aQkZ012fC0G2+cdenNJkTSqlAZfyUhz4RiKKPTPQZ+2L3ajXv7c5huXNnZfmGd6e2Iz3hh5SarV7YPzosj/prVabtdAqqQfLMxu6CGyhomH2SZUaDl7s3fS9VZzb69DP0KwMpD20jY8FkiZM+B32jlApUxrP8jBkzeBv6RCCKNXKmz4GWEPsg0hOeq+Y+tEDJgX6gJVQ+9/sVKuRTn7IkqXe6GVRrpBlan2Sfka0+PZsRVJ+m/KQgnV4t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G280L35sfv1Ytp9A92vDZ30VsnM2hpNBqNWq5KyKzO43WLntjU/OrDZRt+E41Go32JppCqpN74457KeauatZ3bq+hu8SNaFi7pZ5k1ETTHfPQVQ6cNdQ7vmbeqmf6NpvfGhe7N85SSneZ5quTpPJFAnwAAyxJjYqSg/Gfdonkrm10KbK8sdy/ggsuwOM3TzyZrxqf2qPCt21dEns4TCfQJALCs5GARiUQGipdIJGK5KqG40+cc3aHCpdxXLrlLoE8AgGUl/xPHSCTSX7xEIhH3/8OyuNMnH3jKgwqXcl+55C6BPgEAlmVZJ0+eHBkeGR8fL/TYlUfGx8cTiUR7e3tpph9In6XcVy65S6BPAIBlWdaFCxc6OjomJycnJiaKb2IRiUQmJiYmJyc7Ojr6+vpKLX2C9OlZrJT7yjN3CfQJAJiit7e3ra0tFotNTEwUui05ZmJiIhqNtrW19fb2OpUp4vQJz5t5RCn3lZ/cGegTAJBiYGDg1KlTx44dO3zocDHFsWPHOjs76ZGQEkwffZXb3AnoEwAAAAgM9AkAAAAEBvoEAAAAAgN9AgAAAIGBPgEAAIDAQJ8AAABAYKBPAAAAIDDQJwAAABAY6BMAAAAIjJs+AQAAAOBEmj7/bmsPAoFAIBCIQKFebfwSgUAgEAhEoMD9TgAAACAw0CcAAAAQGOgTAAAACAz0CQAAAAQG+gQAAAACoxKXriMQCAQCgQgU0CcCgUAgEIED+kQgEAgEInBAnwgEAoFABI7/Bx1V8vdrqnOCAAAAAElFTkSuQmCC" alt="" />

再次向IE致敬!

寻寻觅觅,终于得知是ContentType问题,这个类型应该设置为text/html才行。这个是在服务端设置的,传给客户端后再转成json的格式来接收。

再看Controller里的action:

 public ActionResult ImportExcel0()
{
if (Request.Files["FileUpload1"] != null && Request.Files["FileUpload1"].ContentLength > )
{
string fileName = System.IO.Path.GetFileName(Request.Files["FileUpload1"].FileName);
//string extension = System.IO.Path.GetExtension(fileName);
string serverPath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), fileName);
if (System.IO.File.Exists(serverPath))
System.IO.File.Delete(serverPath); Request.Files["FileUpload1"].SaveAs(serverPath); try
{
ImportExportData.ImportExcel(serverPath, "BOMs");
ViewBag.Msg = "good";
System.IO.File.Delete(serverPath);
//为避免IE8出现下载文件提示,需将ContentType设置为"text/html"
JsonResult jt = Json(new { success = true, message = "导入成功!", fileName = fileName });
jt.ContentType = "text/html";
return jt;
//增加以上3行代码。注释以下1行代码
//return Json(new { success = true, message = "导入成功!", fileName = fileName });
}
catch (Exception ex)
{
ViewBag.Msg = ex.Message;
System.IO.File.Delete(serverPath);
JsonResult jt = Json(new { success = false, message = "导入失败" + ex.Message, fileName = fileName });
jt.ContentType = "text/html";
return jt;
//return Json(new { success = false, message = "导入失败" + ex.Message, fileName = fileName });
}
}
return View("Index");
}

这样一来居然把上面出现的两个问题同时解决了!

本来对于清除input type=file的问题愁肠百转,找到一个方法看起来很厉害的样子:

//清除file文本框的内容
window.reset2 = function (e) {
e.wrap('<form>').closest('form').get(0).reset();
e.unwrap();
}

现在不用纠结了。

注:

javascript代码里有个toastr,这个是个信息提示插件,详情可见:http://kevintsengtw.blogspot.com/2013/03/aspnet-mvc-jquery-form-plugin.html#.UoYcWdLWamQ

一些链接:

http://blog.163.com/rihui_7/blog/static/212285143201361735143401/
http://www.oschina.net/question/223750_123703
http://my.oschina.net/wangr15/blog/160054

深入理解jQuery中$.get、$.post、$.getJSON和$.ajax的用法
http://www.itivy.com/jquery/archive/2011/7/6/jquery-get-post-getjson-ajax.html