最简单的使用MCV4网页进行文件上传

来源:互联网 发布:掉头发 洗发水 知乎 编辑:程序博客网 时间:2024/05/22 15:42

可以参考 http://www.cnblogs.com/CareySon/archive/2009/12/23/1630902.html


//Index.cshtml 视图


@model IEnumerable<SafetyValveForMobile.Models.BusinessModel>


@{
    ViewBag.Title = "Index";
}


<h2>Index</h2>


<form action="Upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" /><br />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
</form>


<p>
    @Html.ActionLink("Create New", "Create")
</p>



//控制器类,可以用Request.Files["file"]获取到文件,其中"file"就是上面的input控件的名字


  public class BusinessController : Controller

    {
        //
        // GET: /Business/


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


        public string Upload()
        {
            foreach (string upload in Request.Files)
            {
                if (! HasFile( Request.Files[upload]) ) continue;
                string path = AppDomain.CurrentDomain.BaseDirectory + "/";
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                Request.Files[upload].SaveAs(Path.Combine(path, filename));
            }
            return "save success";
        }


        public static bool HasFile( HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0) ? true : false;

        }

}
}



项目地址

http://download.csdn.net/detail/findsafety/8946753

0 0