Asp.net mvc4用iframe实现异步上传
1. Model层用一个TestModel(与上一篇博文的TestModel 相同)
2. Controller层:
public class TestController : Controller
{
//这是iframe页面的action
public ActionResult IframeView()
{
return View();
}
public ActionResult View2()
{
return View();
}
/// <summary>
/// 提交方法
/// </summary>
/// <param name="tm">模型数据</param>
/// <param name="file">上传的文件对象,此处的参数名称要与View中的上传标签名称相同</param>
/// <returns></returns>
[HttpPost]
public ActionResult View2(TestModel tm, HttpPostedFileBase file)
{
if (file == null)
{
return Content("没有文件!", "text/plain");
}
var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName));
try
{
file.SaveAs(fileName);
tm.AttachmentPath = fileName;//得到全部model信息
return Content("上传成功!", "text/plain");
}
catch
{
return Content("上传异常 !", "text/plain");
}
}
}
View层,现在有两个View层,一个是iframe,叫IframeView,一个是View2,分别如下:
IframeView
@model UploadFile.Models.TestModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IframeView</title>
</head>
<body>
@*enctype= "multipart/form-data"是必需有的,否则action接收不到相应的file,这里报交的action是View2*@
@using (Html.BeginForm("View2", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(mod => mod.Title)
<br />
@Html.EditorFor(mod => mod.Title)
<br /> <br />
@Html.LabelFor(mod => mod.Content)
<br />
@Html.EditorFor(mod => mod.Content)
<br />
<span>上传文件</span>
<br />
<input type="file" name="file" />
<br />
<br />
<input id="ButtonUpload" type="submit" value="提交" />
}
</body>
</html>
别一个是View2
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>iframe异步上传</title>
</head>
<body>
<form>
<iframe width="500" height="500" src="/Test/IframeView"></iframe>
</form>
</body>
</html>