{#========================================== Demos - HTML Forms - File upload ==========================================#} {% extends "../htmlForms.html" %} {% block demoSectionClasses %}demo_html_forms_single{% endblock %} {% block meta_title %}Demos - HTML Forms - File upload{% endblock %} {% block meta_description %}File upload using Spincast{% endblock %} {% set demoId = "fileUpload" %} {% block demoBody %}
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.
{% if uploadFileBase64ImageSrc is not empty | default(false) %}
Uploaded image :
HTML template (the frontend part) :
fileUpload.html
Uploading a file is very easy. On the client-side : {% verbatim %}
<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.
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 thie 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) {
validation.addError("demoForm.fileToUpload",
"FILE_NOT_KNOWN_IMAGE_TYPE",
"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.
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 those topics in the Validation and Forms sections of the documentation.
{% endblock %}