Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPRequest.Files.Count Never Equals Zero

I have a form on an HTML page that a user needs to use to upload a file which posts to an ASPX page. In the code behind, I want to test if a file has actually been loaded.

if (Request.Files.Count > 0)
{
    DoStuff(Request.Files[0]);
}
else
{
    throw new Exception("A CSV file must be selected for upload.");
}

I am never getting to the else. Is this just how ASP.NET operates? If I have a input element of type file, is it always going to upload a "file" even if one is not selected?

What's the proper way to do this? Maybe this?

if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
    DoStuff(Request.Files[0]);
}
else
{
    throw new Exception("A CSV file must be selected for upload.");
}
like image 557
kzh Avatar asked Dec 10 '10 18:12

kzh


2 Answers

Everything was in place as mentioned above. Adding FormMethod.Post solved my issue.

FormMethod.Post, new { enctype = "multipart/form-data"}
like image 156
Rizwan Avatar answered Nov 12 '22 11:11

Rizwan


Maybe just this will do:

if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
    DoStuff(Request.Files[0]);
}
else
{
    throw new Exception("A CSV file must be selected for upload.");
}
like image 30
kzh Avatar answered Nov 12 '22 11:11

kzh