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

本文介绍了如何在ASP.NET MVC框架中实现文件上传功能,并详细解释了如何通过控制器类接收和处理上传的文件,包括检查文件是否存在、获取文件名及路径,并将文件保存到服务器上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以参考 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.youkuaiyun.com/detail/findsafety/8946753

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值