I have a typical struts2 form with a File selection field:
<s:form action="%{#parameters.myAction}" namespace="/" method="post" name="myForm" enctype="multipart/form-data" focusElement="storeBrandNameId">
<s:textfield name="storeBrandName" id="storeBrandNameId" size="40" maxlength="50" required="true" key="storeBrandName-label" tooltip="%{getText('storeBrandName-label-help')}" />
<s:file name="storeImage" key="storeImage-label"/>
/* ... Other fields removed for clarity ... */
<s:submit key="submit" />
</s:form>
The form works fine, except when I have a validation error (using XML validation). In that case, all the fields values are preserved except the selected file (if any).
Why is the selected file cleared on validation error? Is it a bug on my side? a struts2 limitation? or a typical browser limitation? Is there a way around?
The value of a file input field cannot be changed or initialized for security reason.
In your form, you have two fields, the text-field, and the file-field.
I don’t think users will care if they loose the value of the input field when the file they selected was wrong. They will be annoyed only when the value in the text-field was wrong, and because of that they need to pick-up the file again.
So you could just do an ajax validation for the text-field value before submitting the form (or better, as they type the value!). If there is a problem, the form is not submitted, user fixes it and don’t loose the file-field value.