templates.demos.htmlForms.fileUpload.html Maven / Gradle / Ivy
Show all versions of spincast-website Show documentation
{% 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 %}
File Upload
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 :
{% endif %}
Code
-
The controller (the backend part) :
DemoHtmlFormsFileUploadController.java
-
The
HTML
template (the frontend part) :
fileUpload.html
How to
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 :
-
2 : A form dedicated to the upload of a file
must have the
enctype="multipart/form-data"
attribute.
-
6 : The
file
input, with
a meaningful "name"
attribute.
-
10 : The potential
Validation Messages
resulting
from the validation of the file.
{% endverbatim %}
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 :
-
2 : We use the
javax.imageio.ImageIO
class to try to read
the image. It's it's not a valid image, an exception is
thrown.
-
4-6 : We add a
Validation Message
to our form to record the fact that the validation failed.
More info
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.
{% endblock %}