Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning HttpPostedFileBase to view on validation error

When I attempt to upload images to my MVC controller action and there is a validation error, I have to click through each of the buttons and find all of my files again.

If I have a view that consists of

<input type="file" id="file0" name="Files[0]" />
<input type="file" id="file1" name="Files[1]" />

and a controller action like

public ActionResult Create(ModelClass model, IEnumerable<HttpPostedFileBase> Files)
{
    if(ModelState.IsValid)
    {
        //do work
        if(PhotoValidation.IsValid(Files))
        {
            //do work
        }
        else 
        {
            ModelState.AddModelError("","Photos not valid");
        }
    }
    return view(model); // Way to return photos back to the view on modelstate error?
}

The files get posted to the server fine but if there is a model validation error, is there any way to return the model AND the Files so the user doesn't have to upload them again?

like image 447
kevskree Avatar asked Sep 13 '12 21:09

kevskree


1 Answers

This is not possible. The value of a intput type="file" is never used on parsing an HTML page. That's a huge security risk, so no modern browser will allow them to 'retain' values.

If you are sure that your clients are using browser with HTML5 support, you can try using JavaScript File API in order to eliminate postbacks - check following articles:

  • Working with files in JavaScript, Part 1: The Basics
  • Working with files in JavaScript, Part 2: FileReader
  • Working with files in JavaScript, Part 3: Progress events and errors
  • Working with files in JavaScript, Part 4: Object URLs
  • Working with files in JavaScript, Part 5: Blobs
like image 161
tpeczek Avatar answered Oct 27 '22 17:10

tpeczek