Resh32
Resh32

Reputation: 6590

Struts2 - file selection field value disappears on validation error

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?

Upvotes: 3

Views: 2112

Answers (3)

Dave Newton
Dave Newton

Reputation: 160251

File fields may not be pre-filled; this is an HTML thing, for security purposes.

If a file was already uploaded, you could remember that and offer to use the just-uploaded file. I'd still show the file input box. This would (slightly) complicate validation.

Upvotes: 2

Alban
Alban

Reputation: 1943

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.

Upvotes: 2

Umesh Awasthi
Umesh Awasthi

Reputation: 23587

Well this is a normal use-case and you need to handle this in order to preserve data and show the selected values to the user even on validation error.

Normally validation error let workflow interceptor to redirect back to the page and show the page with errors, which means your actual method never got called.

Struts2 provides a way to prepare any data you need for your action to work properly.User Preparable interface and use its prepare method.

Its prepare() method get called before the validation and you can set any values required to show if there is any error.

In short prepare() method work as init method to do any such sort of work

Upvotes: 1

Related Questions