MVC中上传文件

与asp.net中几乎一样,使用表单提交的方式上传文件(如果是使用了第三方插件的话,那么就另当别论)

@{
    ViewBag.Title = "Index";
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>@ViewBag.Title</title>    
</head>
<body>
    <form id="form1" method="post"  enctype="multipart/form-data" action="@Url.Action("SaveFiles")">
        <input type="file" name="file" value="" />
        <br />
        <input type="submit" value="提交" /> 
    </form>
</body>
</html>
View中的代码
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace PartyInvites.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

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

        [HttpPost]
        public ActionResult SaveFiles()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file == null)
            {
                return Content("没有文件!", "text/plain");
            }
            var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName));            
            try
            {
                file.SaveAs(fileName);
                return Content("上传成功!", "text/plain");      
            }
            catch 
            {
                return Content("上传异常!","text/plain");               
            }            
        }
    }
}
controller中代码
原文地址:https://www.cnblogs.com/vichin/p/10208455.html