ASP.NET MVC- Upload File的例子

  上傳文件是一項基本功能,必定要了解的。先來看一下使用ASP.NET MVC實現簡單的上傳。html

1、簡單的例子spa

  Controller的例子code

        public ActionResult UploadDemo()
        {
            return View();
        }


        public ActionResult FileUpload()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file != null)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName));
                file.SaveAs(filePath);

                Response.Write("<script>alert('上傳成功');location.href='/Index/UploadDemo' </script>");
            }
            else
            {
                Response.Write("<script>alert('上傳失敗');location.href='/Index/UploadDemo' </script>");
            }

            return null;
        }

  對應的View視圖orm

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>UploadDemo</title>
</head>
<body>
    <div>
        <h2>
            上傳例子</h2>
        @using (Html.BeginForm("FileUpload", "Index", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <input type="file" name="file" />
            <input type="submit" value="uploadFile" />
        }
    </div>
</body>
</html>
相關文章
相關標籤/搜索