ASP.NET MVC使用模型绑定接收上传文件

来源:互联网 发布:2016网络暴力案例 编辑:程序博客网 时间:2024/05/16 04:56

今天有人问我上传文件怎么做,说百度也没找到。

不多BB,直接上代码。

控制器代码:

 // 文件上传        // POST访问 /Home/Upload        [HttpPost]        public ActionResult Upload(HttpPostedFileBase file)        {            if (file != null)            {                if (file.ContentLength == 0)                {                    // 文件大小(以字节为单位)为0,返回视图                    return View();                }                else                {                    //保存文件                    //应用程序需要有服务器UploadFile文件夹的访问权限                    file.SaveAs(Server.MapPath("~/UploadFile/" + file.FileName));                }            }            return View();        }

前台代码:

<body>     <h1>文件上传</h1>    @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {        <text>选择上传文件:</text><input name="file" type="file" id="file" />        <br />        <br />        <input type="submit" name="submit1" value="上传" />    }</body>