{% 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 %}
{{validation['demoForm.fileToUpload'] | validationMessages()}}
Validations to test :
  • 1. The file needs to be a valid image.
  • 2. The file must be 200KB or less.

Code

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 :

{% 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 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 :

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 those topics in the Validation and Forms sections of the documentation.

{% endblock %}