今天写了一个使用MVC上传的DEMO,很简单不超过10行代码。代码如下(关注重点,所以尽量精简掉其他代码):
- 项目结构
- 控制器代码
public ActionResult Index() { return View(); } [HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file == null) { return Content("没有文件!"); } var filename = Path.Combine(Request.MapPath("~/upload"), Path.GetFileName(file.FileName)); file.SaveAs(filename); return Content("OK"); }
- 视图代码
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <form enctype="multipart/form-data" method="post" action="uploadfile/Upload"> <input type="file" name="file" /> <button type="submit">上传</button> </form> </div> </body> </html>
- 一些值得注意的地方:
- input标签的name要和update方法的参数的名字一致。