ASP.NET MVC- Upload File的例子

  上传文件是一项基本功能,一定要了解的。先来看一下使用ASP.NET MVC实现简单的上传。

一、简单的例子

  Controller的例子

        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视图

@{
    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>
原文地址:https://www.cnblogs.com/cxeye/p/4988604.html