3

我在 asp.net mvc 2 中上传文件时遇到问题。我的控制器函数的参数是一个FormCollection类型。因为字段太多,我无法将每个字段单独作为参数。我的表单中有 2 个上传文件字段。如何在控制器中获取上传的文件?

我试过这样:

public ActionResult CreateAgent(FormCollection collection, HttpPostedFileBase personImage)
{
    ...
}

但是personImagenull。:(

或者这样:

HttpPostedFileBase img = this.HttpContext.Request.Files[collection["personImage"]];

imgnull。也是collection["personImage"]所选文件的名称(没有路径),我无法将其转换为HttpPostedFileBase.

请注意,所有字段都必须在一页上填写。我不能让客户在单独的页面上传图片!

4

2 回答 2

9

从阅读这篇博文开始。然后将其应用于您的场景:

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

    <input type="file" name="file1" id="file" />
    <input type="file" name="file2" id="file" />

    ... Some other input fields for which we don't care at the moment
        and for which you definetely should create a view model
        instead of using FormCollection in your controller action

    <input type="submit" />
</form>

用 WebForms 语言翻译的结果是:

<% using (Html.BeginForm("CreateAgent", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    <input type="file" name="file1" id="file" />
    <input type="file" name="file2" id="file" />

    ... Some other input fields for which we don't care at the moment
        and for which you definetely should create a view model
        instead of using FormCollection in your controller action

    <input type="submit" />
<% } %>

进而:

public ActionResult CreateAgent(
    // TODO: To be replaced by a strongly typed view model as the 
    // ugliness of FormCollection is indescribable
    FormCollection collection, 
    HttpPostedFileBase file1, 
    HttpPostedFileBase file2
)
{
    // use file1 and file2 here which are the names of the corresponding
    // form input fields
}

如果您有很多文件IEnumerable<HttpPostedFileBase>,请按照 Haacked 的说明使用。

评论:

  • 绝对不要this.HttpContext.Request.Files在 ASP.NET MVC 应用程序中使用
  • 绝对永远永远永远不要this.HttpContext.Request.Files[collection["personImage"]]在 ASP.NET MVC 应用程序中使用。
于 2011-04-11T20:50:30.023 回答
2

在您的表单视图中,您的 using 语句是什么样的?它应该看起来像这样:

using (Html.BeginForm("CreateAgent", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })
于 2011-04-11T20:50:00.703 回答