MAQNH

记录开发过程中的点点滴滴。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

今天写了一个使用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");
    }
    View Code
  • 视图代码
    @{
        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>
    View Code
  • 一些值得注意的地方:
    • input标签的name要和update方法的参数的名字一致。
posted on 2014-08-17 15:49  MAQNH  阅读(202)  评论(0编辑  收藏  举报