Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request.File.Count is still set to 1 when File Upload in ASP.Net MVC encountered a previous error

Tags:

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!

like image 364
mallows98 Avatar asked Aug 05 '09 03:08

mallows98


1 Answers

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... 
     }
 }
like image 110
Jason Underhill Avatar answered Oct 02 '22 12:10

Jason Underhill