Why IEnumerable count is 1 whe

2019-06-06 04:25发布

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条回答
地球回转人心会变
2楼-- · 2019-06-06 04:50

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);
                    }
                }
查看更多
登录 后发表回答