Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving value for <form:input type="file"> with Spring MVC

I have a form with two inputs: one string, one file.

<form:form ...>
  <form:input type="text" ....>
  <form:input type="file" ....>
</form:form>

If the validation fails on the string input, the controller routes back to this same view. When that happens, the string field is preserved but the selected file is lost.

Is there a way to preserve the file selected when the view is re-rendered?

I think the answer is no - and that it is intrinsic to the HTML file input, not the server-side framework. Asking in case there's something I'm missing.

like image 952
wrschneider Avatar asked Mar 19 '13 21:03

wrschneider


1 Answers

It is true that the file input value cannot be preserved. Thats just as it is implemented in all browsers. As far as i can tell it has to do with potential security risks but i never went deeper.

There is a possibility to achieve something similar though. This is what we did in our project:

  • Each form with fileupload has a UUID that will not change as long as inputs are invalid.
  • We used FineUploader to asynchronosly upload files during these edit phase(s) which uploads to a folder with this uuid as foldername
  • We maintain hidden inputs (text) with references to the current uploads
  • If there are not bindingresult errors we process the files in a method and oncomplete we remove the upload folder
  • If there is an error we keep the uuid in place and maintain the input fields so we do not loose the references.

This works stable now and as a nice side effect the controller was somehow easier and in my eyes also cleaner to write since we do not need multipart for these forms anymore and another controller just handling uploads.

Edit: - you might want to implement a cronjob to clear abandonned uploads!

like image 168
Martin Frey Avatar answered Nov 20 '22 12:11

Martin Frey