上传多个文件时,为什么HttpPostedFileBase的列表为空?

问题描述:

在客户端,我有以下代码:上传多个文件时,为什么HttpPostedFileBase的列表为空?

<form action="@Url.Action("UploadStatistics")" method="POST" enctype="multipart/form-data"> 
<h4>Upload Statistics Excel file(s)</h4> 
<p> 
    <input type="file" name="file" id="file" multiple/> 
</p> 

<input type="submit" onclick="ClearDirtyFlag();" /> 

因此,用户可以选择多个文件进行上传。

在服务器端我有这样的代码:

public ViewResult UploadStatistics(List<HttpPostedFileBase> files) 
{ 
    //the issue is that the files parameter comes null... 
} 

注意:如果我不希望HttpPostedFileBase对象列表(只是只有HttpPostedFileBase参数)时,代码工作得很好...

任何人都可以告诉我这里有什么问题吗?

此致敬礼。

+1

'name =“file”'不匹配y我们的参数名称(复数)。将其更改为'name =“files”'(或将参数设置为'List 文件') –

+0

@StephenMuecke谢谢你,它完美地工作。如果你愿意,请写下这个答案,以便我能接受它,也许它会帮助别人。 –

您的输入有name="file"但您的POST方法中的参数名为files - 它们不匹配。改变输入到

<input type="file" name="files" id="file" multiple/> 

或更好,有一个视图模型与属性

public IEnumerable<HttpPostedFileBase> Files { get; set; } 

,并强烈地结合使用

@Html.TextBoxFor(m => m.Files, new { type = "file" }) 

它给你的是额外的好处模型能够应用验证属性并获得客户端和服务器端验证