HttpPostedFileBase错误(文件对象为null)

时间:2018-10-14 14:30:24

标签: c# asp.net asp.net-mvc model-view-controller

我的html文件index.cshtml就是这样

<html>
<head>
</head>
<body>
    <form method="post">
        <input type="file" name="myfile" id="myfile" />
        <input type="submit" value="Upload" />
    </form>
</body>
</html>

我的控制器就是这样

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase myfile)
        {
            string currentdir = Directory.GetCurrentDirectory();

            myfile.SaveAs(currentdir + "\\" + myfile.FileName);

            return View();
        }
    }

当我发布文件时发生错误。它告诉myfile对象为null。请帮助解决此问题。太感谢了!

2 个答案:

答案 0 :(得分:2)

在如下所示的表单标签中添加enctype属性,

<form method="post" enctype="multipart/form-data">

答案 1 :(得分:1)

<html>
<head>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="myfile" id="myfile" />
        <input type="submit" value="Upload" />
    </form>
</body>
</html>