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>