问题
I have a multiple upload form and I want to check if there is any files when I launch the upload. Here is my code.
View :
@using (Html.BeginForm("Upload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data"}))
{
<input name="files" type="file" multiple="multiple" />
<input type="submit" value="Upload" />
}
Controller :
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files.Count() > 0) Console.WriteLine(files.Count()); // display 1
if(files.Any()) Console.WriteLine(files.Any()); // display true
if (files.First() == null) Console.WriteLine("first null"); // display "first null"
return View();
}
Why my program display results like that when I submit an empty form ?
I'll probably check with JS my field, but I want to understand what is these data in my IEnumerable<HttpPostedFileBase>
. Thank you.
回答1:
Though i am a little late for the party but still. I had a same issue. Found an article on asp.net they said that its by design. http://aspnetwebstack.codeplex.com/workitem/188
This is by design because the request contains that segment which has filename="". If you don't want to have the file created, please remove that segment from the request. I fixed it via the following way.
if (RelatedFiles.Any())
{
foreach (var file in RelatedFiles)
{
if (file != null) // here is just check for a null value.
{
byte[] uploadedFile = new byte[file.InputStream.Length];
file.InputStream.Read(uploadedFile, 0, file.ContentLength);
FileInfo fi = new FileInfo(file.FileName);
var upload = new UploadedFile
{
ContentType = file.ContentType,
Content = uploadedFile,
FileName = fi.Name,
ContentExtension = fi.Extension,
};
newIssuePaper.RelatedDocuments.Add(upload);
}
}
来源:https://stackoverflow.com/questions/17614892/why-ienumerablehttppostedfilebase-count-is-1-when-i-upload-0-files