ASP.NET MVC文件上传简单示例

一. 前端代码

 @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
        {
            <div>文件上传:<input type="file" name="myFile"/></div>
            <input type="submit" value="提交"/>
        }

 

二. 后端代码

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost]
        public ActionResult UploadFile()
        {
            HttpPostedFileBase file = Request.Files["myFile"];
            if (file != null)
            {
                try
                {
                    //检查是否存在文件夹
                    string subPath = "D:\\pic";
                    if (false == System.IO.Directory.Exists(subPath))
                    {
                        //创建pic文件夹
                        System.IO.Directory.CreateDirectory(subPath);
                    }                                  
                    var filename = Path.Combine("D:\\pic", file.FileName);  //Path.Combine(Request.MapPath("~/Upload"), file.FileName); MapPath:虚拟目录
                    file.SaveAs(filename);
                    return Content("上传完成");
                }
                catch (Exception ex)
                {
                    return Content(string.Format("上传文件出现异常:{0}", ex.Message));
                }

            }
            else
            {
                return Content("没有文件需要上传!");
            }
        }

 

ASP.NET MVC文件上传简单示例

上一篇:html中使用include引入另一个html文件


下一篇:php去除html标签及空格回车