Asp.net mvc4用iframe實現異步上傳

1.         Model層用一個TestModel(與上一篇博文的TestModel 相同)html

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>異步

相關文章
相關標籤/搜索