HTTPRequest.Files.Count 永远不等于零
我在 HTML 页面上有一个表单,用户需要使用该表单来上传发布到 ASPX 页面的文件。在后面的代码中,我想测试文件是否已实际加载。
if (Request.Files.Count > 0)
{
DoStuff(Request.Files[0]);
}
else
{
throw new Exception("A CSV file must be selected for upload.");
}
我永远不会谈到其他。这就是 ASP.NET 的运行方式吗?如果我有一个文件类型的输入元素,即使没有选择一个“文件”,它是否总是会上传一个“文件”?
执行此操作的正确方法是什么?也许是这个?
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.");
}
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.");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许这样就可以了:
Maybe just this will do:
Request.Files.Count
始终包含编号。表单中的元素,包装在
Key:Value
存储中。因此,如果您发布的表单不包含任何
标记,则
Request.Files.Count
将返回0
代码>.每个
Key
都是的
name
,其值的类型为 <代码>HttpPostedFileWrapper。请参阅此处了解
HttpPostedFileWrapper
。Request.Files.Count
always contains the no. of<input type="file">
elements in your form, wrapped in aKey:Value
store.Hence, if your posted form does not contain any
<input type="file">
tags, thenRequest.Files.Count
will return0
.Each
Key
is thename
of the<input type="file" name="OneOfTheKeys">
and the value is of typeHttpPostedFileWrapper
.See here to learn about
HttpPostedFileWrapper
.您应该使用 FileUpload 控件并检查 .HasFiles 以查看是否上传了任何内容。
http://msdn.microsoft.com/en -us/library/system.web.ui.webcontrols.fileupload.aspx
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
如上所述,一切都已就位。添加
FormMethod.Post
解决了我的问题。Everything was in place as mentioned above. Adding
FormMethod.Post
solved my issue.我还要确保 .count 方法返回的数据不是字符串。字符串值 '0' 始终大于 int 值 0;在这种情况下,它总是返回 true。
我会尝试将 .count 返回类型转换为 int 以确保比较正确的类型。即使字符串“-1”的位值也比 int 0 更高。
只是一个想法,虽然我可能是错的......
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....