在MVC中实现文件的上传

  @using (Html.BeginForm("daoru", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))

        {  <input id="File1" type="file" name="FileName" />

            <input type="submit" value="导入" />

        }

new { enctype = "multipart/form-data" }必不可少,不认上传不能成功!

 

public ActionResult daoru(FormCollection form, string FileName)

        {

            //GoodsDBDataContext BDataContext = new GoodsDBDataContext();

            //清空系统缓存

            string path = Server.MapPath("~/File");

            Directory.Delete(path, true);

            Directory.CreateDirectory(path);

            //判断是否有文件

            if (Request.Files.Count == 0)

            {

                return View("Index");

            }

            //得到上传的文件

            var file = Request.Files[0];

            if (file.ContentLength == 0)

            {

                return View("Index");

            }

            else

            {

                //上传文件,exc.xlsx就是你上上传的值

                HttpPostedFileBase file1 = Request.Files[0];

                string path1 = Path.Combine(path, "exc.xlsx");

                file1.SaveAs(path1);

            }

}

posted @ 2016-06-22 16:16  方金  阅读(252)  评论(0编辑  收藏  举报