Abida
Abida

Reputation: 233

Retaining the value in the <input type="file"> field when submit button is clicked

I have got a <input type="file" > field along with other text fields in a form, When i try to upload any files using browse button and then click submit button ,the value in the input type= "file" field disappears , I would like the browsed value to remain in the <input type="file" > field if errors are present in other fields , is there any way i can retain the value that is browsed and for it to remain in the <input type="file" > field when submit button is clicked ,

<form action="form.php" method="post" enctype= multipart/form-data> 

<input type="file" value="$file" name="file"/> 
<input type="text" value="$line" name="line"> 
 <input type="submit"  name="btnsubmit"> 

</form> 

if($_POST['btnsubmit']) 
{
$line =$_POST['line'];
$file =$_FILES['file'] ['name'];

if($line) 
{
//do something
//conditions for   file check   here 

}
else 
//error 

}

Upvotes: 13

Views: 27714

Answers (4)

SpliFF
SpliFF

Reputation: 39004

There is one way to do this. Submit the form details for validation using an AJAX submission method so the user never really leaves the page or "submits" the form. That way you can validate the result server-side but the user still has all their values populated, including file inputs.

Upvotes: 1

J&#248;rgen
J&#248;rgen

Reputation: 9130

As mentioned, input[type=file] is readonly. By validating your input on the client side, you can prevent the submit to happen unless all fields are valid. ...and, in most cases, it provides a much better user experience!

Check out jquery.validation or some other validation plugin for your favourite framework, or write one yourself. Keep in mind that you should also validate on the server side.

By preventing the request, the file input will keep it's value until all fields are OK. If you need server side validation, you could also do this using ajax.

Upvotes: 0

Aditya M P
Aditya M P

Reputation: 5347

It is not possible to do this. Browser security prevents you from pre-populating the File input field, so that websites cannot steal private files of their will without the user authorizing it first (by clicking "Browse..." and choosing a file).

EDIT: It is not possible to do this natively - but you can attempt some CSS wizardry to display the previously chosen file name maybe beside the file input box to hint the user. If you want to try and be really cool, you can also attempt to overlay the browser's native file input text display area with another div that has the previous file name filled in it. But this will prevent clicking on the input area and so is user unfriendly. Too much work, little reward.

Upvotes: 9

Rab
Rab

Reputation: 35572

This not allowed to be set by any script for security purpose, implemented by browser vendors as file input as readonly.

Upvotes: 1

Related Questions