0

我不知道我错过了什么,但我需要使用 C# MVC 3 上传文件。我按照 SO 中的说明进行操作,但文件始终为空。

这是我的实际测试代码:

HTML

@using (Html.BeginForm("Prc", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   <input type="file" name="file" id="file" />
   <input type="submit" value="submit" />
}

控制器

[HttpPost]
public ActionResult Prc(HttpPostedFile file)
{
    if (file != null && file.ContentLength > 0)
    {
        var filename = System.IO.Path.GetFileName(file.FileName);
        var path = System.IO.Path.Combine(Server.MapPath("~/Content/Images"), filename);
        file.SaveAs(path);            
     }

     return RedirectToAction("Index");
 }

当我运行 Web 应用程序时,我附加了一个文件,然后单击提交。但是当我到达时Controllerfile对象是null。总是null。我尝试了一个XML文件,一个JPEG文件和一个GIF文件,但没有一个起作用。

除了这些代码之外我还应该配置其他东西吗?

谢谢

4

2 回答 2

2

One more thing might trip you up.

Using asp.net mvc 3 razor, I was just surprised to discover that the name of the HttpPostedFileBase variable passed to the controller method must match the id and name of the file input tag on the the view. Otherwise asp.net passes null for the HttpPostedFileBase variable.

For example, if your file input looks like this: < input type="file" name="filex" id="filex" />

And your controller method looks like this: public ActionResult Uploadfile(HttpPostedFileBase filey)

You'll get NULL for the "filey" variable. But rename "filey" to "filex" in your controller method and it posts the file successfully.

于 2013-04-01T19:46:06.617 回答
2

在 MVC 中,您需要使用HttpPostedFileBase而不是HttpPostedFile

[HttpPost]
public ActionResult Prc(HttpPostedFileBase file)
{
    //...
}
于 2012-08-10T09:23:46.083 回答