使用Request.Files [“ files”] MVC上传多个文件

Neg*_*gar 1 asp.net-mvc-2

这是我的代码。我想将3个文件上传到我的数据库中

首先在View中,我这样写:<%using(Html.BeginForm(Actionname,Controller,FormMethod.Post,new {enctype =“ multipart / form-data”})){%> ..... ....

这是3个文件更新:

<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />
Run Code Online (Sandbox Code Playgroud)

在控制器中,我使用以下代码:

IEnumerable<HttpPostedFileBase> files = Request.Files["files"] as IEnumerable<HttpPostedFileBase>;
foreach (var file in files)
{
byte[] binaryData = null;
HttpPostedFileBase uploadedFile = file;
if (uploadedFile != null && uploadedFile.ContentLength > 0){
 binaryData = new byte[uploadedFile.ContentLength];
 uploadedFile.InputStream.Read(binaryData, 0,uploadedFile.ContentLength);
}
}
Run Code Online (Sandbox Code Playgroud)

但是文件总是返回NULL :(

请帮助我,谢谢。

Dar*_*rov 5

尝试以下方法:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>
    <input type="file" name="files" id="FileUpload1" />
    <input type="file" name="files" id="FileUpload2" />
    <input type="file" name="files" id="FileUpload3" />
    <input type="submit" value="Upload" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

和相应的控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                // TODO: do something with the uploaded file here
            }
        }
        return RedirectToAction("Index");
    }
}
Run Code Online (Sandbox Code Playgroud)

有点干净。