在ASP.NET MVC中上传文件(再次!)

Jal*_*lal 3 .net upload file-upload httppostedfile asp.net-mvc-2

我在asp.net mvc 2中上传文件时遇到问题.我的控制器功能参数是一种FormCollection类型.由于字段数太多,我不能将每个字段作为参数分开.我的表单中有2个上传文件字段.如何在控制器中上传文件?

我试过这种方式:

public ActionResult CreateAgent(FormCollection collection, HttpPostedFileBase personImage)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

personImagenull.:(

或者这样:

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

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

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

Dar*_*rov 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>
Run Code Online (Sandbox Code Playgroud)

用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" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

然后:

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
}
Run Code Online (Sandbox Code Playgroud)

如果你有很多文件,那么IEnumerable<HttpPostedFileBase>就像Haacked所说的那样使用.

备注:

  • 绝对不会this.HttpContext.Request.Files在ASP.NET MVC应用程序中使用
  • 绝对永远不会永远不会this.HttpContext.Request.Files[collection["personImage"]]在ASP.NET MVC应用程序中使用.