Why IEnumerable<HttpPostedFileBase> count is 1 when I upload 0 files?

删除回忆录丶 提交于 2019-12-10 11:45:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!