Select a file and submit it.
Only an image of less than 200KB will be accepted! Otherwise, you're going to see some validation messages.
HTML
template (the frontend part) :
fileUpload.html
Uploading a file is very easy. On the client-side :
<form action="#form" method="post" accept-charset="UTF-8" enctype="multipart/form-data"> //... <input type="file" name="demoForm.fileToUpload" /> // ... {{validation['demoForm.fileToUpload'] | validationMessages()}} // ... <button id="subBtn" type="submit" class="btn btn-primary">Submit</button> </form>
Explanation :
enctype="multipart/form-data"
attribute.
file
input, with
a meaningful "name"
attribute.
Validation Messages
resulting
from the validation of the file.
On the server side, we get the uploaded file using its "name"
. Note that
multiple uploaded files can have the same name, but since we only have one here, we
use the getUploadedFileFirst(...)
method from our
Request Context :
File uploadedFile = context.request().getUploadedFileFirst("demoForm.fileToUpload");
We can then run validation on this file and process it. Here's for example how we validate that it is actually an image :
try { ImageIO.read(uploadedFile).toString(); } catch(Exception e) { form.addError("fileToUpload", "fileToUpload_notValidImage", "The file must be a valid image of type PNG, JPEG, GIF or BMP."); }
Explanation :
javax.imageio.ImageIO
class to try to read
the image. It's it's not a valid image, an exception is
thrown.
Validation Message
to our form to record the fact that the validation failed.
Make sure you also try the first demo of this section, Introduction - Single field which introduces forms and validation using Spincast.
Otherwise, you can learn everything about forms and validation in the dedicated Forms section of the documentation.