MVC4.0 上传文件

Views/Import/ImportExcel.cshtml

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ImportExcel</title>
<script src="@Url.Content("~/Content/Jquery.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
if ('@ViewBag.tip' != "") {
alert('@ViewBag.tip');
}
});
</script>
</head>
<body>
<form action='@Url.Action("/ImportExcel")' method="post" enctype="multipart/form-data">
<input type="text" name="fname" />
<input type="file" name="f1" runat="server"/><br />
<input type="text" name="fname2" />
<input type="file" name="f2" runat="server"/><br />
<input type="submit" name="ids" value="提交" />
</form>
</body>
</html>

---以上绿色部分必须有,controller中fc.count才能不等于0

Controllers/ImportController.cs

[HttpGet]
public ActionResult ImportExcel()
{
return View();
}
[HttpPost]
public ActionResult ImportExcel(string aburl)
{
try
{
HttpFileCollectionBase fc = Request.Files;
int ll = fc.Count;
HttpPostedFileBase f = Request.Files[0];
HttpPostedFileBase f2 = Request.Files[1];
if (!Directory.Exists(Server.MapPath("~/VersionApk")))
{
Directory.CreateDirectory(Server.MapPath("~/VersionApk"));
}
string ext = f.FileName.Substring(f.FileName.LastIndexOf("."));
string ext2 = f2.FileName.Substring(f2.FileName.LastIndexOf("."));
string fn = Request.Form["fname"].ToString();
string fn2 = Request.Form["fname2"].ToString();
f.SaveAs(Server.MapPath("~/VersionApk") + "\" + fn + ext);
f2.SaveAs(Server.MapPath("~/VersionApk") + "\" + fn2 + ext2);
ViewBag.tip = "上传成功!";
}
catch { ViewBag.tip = "上传失败!"; }
return View("ImportExcel");
}

原文地址:https://www.cnblogs.com/jcz1206/p/3483512.html