Forms & Validation demos

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.

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 :


<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.

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.