【问题标题】:MVC 3 input file always nullMVC 3 输入文件始终为空
【发布时间】:2011-11-10 17:25:48
【问题描述】:

我添加了一个输入文件字段,但它在控制器上始终为空。我错过了什么?

这是我的视图和控制器的代码。

查看:

...
@using (Html.BeginForm())
{
    ...

    <input type=file name="file" id="file" class="post-attachment" />

    ...
}

控制器:

[HttpPost]
public ViewResult _Details(HttpPostedFileBase file, ViewTopic viewTopic, string SearchField, string submitBtn)
{
    // save file to server
    if (file != null && file.ContentLength > 0)
    {
        var fileName = DateTime.Today.ToString("yy.MM.dd") + Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/Attachments"), fileName);
        file.SaveAs(path);
    }

...
}

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    需要显式设置表单的enctype

    @using(Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        ...
    }
    

    【讨论】:

    • 工作。谢谢!虽然文件似乎有限制,因为它一直有一个可能是文件大小或文件类型的错误,但我将其保存为另一个问题。
    【解决方案2】:

    您需要将表单更改为 -

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

    这个问题中有更多信息(包括上面的示例) - Html helper for <input type="file" />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-06
      • 2015-12-07
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多