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.");
}
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.");
}
Request.Files.Count
always contains the no. of <input type="file">
elements in your form, wrapped in a Key:Value
store.
Hence, if your posted form does not contain any <input type="file">
tags, then Request.Files.Count
will return 0
.
Each Key
is the name
of the <input type="file" name="OneOfTheKeys">
and the value is of type HttpPostedFileWrapper
.
See here to learn about HttpPostedFileWrapper
.
You should use the FileUpload control and check .HasFiles to see if anything was uploaded.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx
Everything was in place as mentioned above. Adding FormMethod.Post
solved my issue.
FormMethod.Post, new { enctype = "multipart/form-data"}
I would also make sure that the data being return by the .count method is not a string. A string value of '0' is always greater than a int value of 0; which would always return true in that condition.
I would try typecasting the .count return as an int to make sure that proper types are being compared. Even a string '-1' has a higher bit value than int zero.
just a thought, though I could be wrong....
精彩评论