tags:

views:

22

answers:

3

I have an HTML form with several text inputs and one file.

If any of the inputs are invalid, the form is shown again to the user with their previous answers as the default values. I know how to do this with text inputs but is there a way to do this with the file?

+3  A: 

You won't be able to do this with the file-input as this would present security issues. Instead, consider performing some client-side validation upon submit. Within the client-side logic, determine whether the submit should be aborted (before a page-refresh occurs) or if it should be permitted to follow through (sending your data and file to the server).

As a suggestion, the jQuery Validation plugin is extremely well-constructed a very popular amongst client-side developers. I would encourage you to consider it for if you decide to tackle client-side validation.

Important: Client-side validation is not a substitution for server-side validation. It is meant only to supplement validation logic already in place on the server.

Jonathan Sampson
+1 for mention of the fact that client-side validation is not secure. (see http://thedailywtf.com/Articles/So-You-Hacked-Our-Site!.aspx for a laugh)
icktoofay
A: 

Nope, there is no way unfortunately do so because of security reasons. :(

Sarfraz
A: 

As others have said, you can't pre- (or re-) populate a file input field. And neither should you, since the user would have to upload the file again and again every time she submits the form.

The simplest thing you can do is to simply hold onto the file in a Session and present the user a notice that there's a file already uploaded. If the user chooses to upload another file, replace the one in the Session.

Pseudocode:

if ($_POST) // upon upload
{
   $saved_file_name = save_image_somewhere($_POST['file'])
   $_SESSION['file'] = $saved_file_name
}

...

if ($_SESSION['file'])
{
    <p>Uploaded file: { echo $_SESSION['file'] }</p>
    <p>Select another file below if you want to replace it.</p>
}
<input type="file" />
deceze