文件上传MVC

Mal*_*olm 9 asp.net-mvc

在我的视图中使用以下标记:

<form action="Categories/Upload" enctype="multipart/form-data" method="post">
    <input type="file" name="Image">
    <input type="submit" value"Save">
</form>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

public ActionResult Upload(FormCollection form)
{
    var file = form["Image"];
}
Run Code Online (Sandbox Code Playgroud)

文件的值是null.如果我使用不同的控制器控制器在不同的视图中尝试它,它使用相同的代码.

我在Vista上有VS2008,MVC 1.0.

为什么?

马尔科姆

Dan*_*ite 34

使用HttpPostedFileBase作为您的操作参数.另外,添加AcceptVerb属性设置为POST.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(HttpPostedFileBase image)
{
    if ( image != null ) {
        // do something
    }
    return View();
}
Run Code Online (Sandbox Code Playgroud)

这段代码完全符合ASP.NET MVC的精神/设计.

  • 我花了几个小时进入圈子,因为我的文件输入标签有一个"ID ="属性,但不是"NAME =" - 请确保包含"name = ..."或文件将发布到actionresult,但是会是空的.希望这有助于某人. (2认同)

Bre*_*gby 7

不要在这里或任何东西挑剔,但这里的代码应该是如何看的,因为丹尼尔在他提供的代码中遗漏了一些细微的细节......

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadPlotImage(HttpPostedFileBase image)
{    
    if ( image != null ) 
    {        
        // do something    
    }

    return View();
}
Run Code Online (Sandbox Code Playgroud)


Ped*_*tos 6

试试这段代码:

    public ActionResult Upload()
    {
        foreach (string file in Request.Files)
        {
            var hpf = this.Request.Files[file];
            if (hpf.ContentLength == 0)
            {
                continue;
            }

            string savedFileName = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory, "PutYourUploadDirectoryHere");
                savedFileName = Path.Combine(savedFileName, Path.GetFileName(hpf.FileName));

            hpf.SaveAs(savedFileName);
        }

    ...
    }
Run Code Online (Sandbox Code Playgroud)