I'm developing a form in ASP.Net MVC where it contains an <input type="file" />
which is not mandatory in a form.
In my controller, I have this code:
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Create(FormCollection collection) {
...
//get uploaded file
if (Request.Files.Count > 0)
{
file = Request.Files["imgFileUpload"];
if (file.ContentLength == 0)
{
throw new InvalidOperationException("File contents are empty");
}
...
}
...
}
Now, when a user uploads a file that has no content, the form would raise an exception and prompt the user about it -- which is expected.
Now, if a user decided that they are not going to upload any file anymore and click the submit button, the previous exception would still show, which is quite bizzare.
I've tried checking the values for Request.Files
and noticed that its count is still set to 1... it still thinks that there is a file there, given that the user has not placed any file on the <input type="file" />
control.
Has anybody encountered this? If so, what steps did you do to prevent from re-executing the previous exception again?
Thank you so much!
I've just experienced the same issue in a similar scenario, I did the following to fix it:
if(Request.Files.Count > 0)
{
if(Request.Files[0].ContentLength > 0)
{
//Upload the file...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With