Oleg Golovanov
Oleg Golovanov

Reputation: 924

How to validate file upload? [Play Framework]

I have a simple bean, like that:

package models;

import play.data.validation.Constraints;

public class Upload
{
    @Constraints.Required
    @Constraints.MinLength(4)
    @Constraints.MaxLength(40)
    public String name;

    @Constraints.Required
    public String inputFile;
}

and form, like that:

@form(action = routes.Application.submit(), 'enctype -> "multipart/form-data") {

    @inputText(
        uploadForm("name"),
        '_label -> "Name"
    )

    @inputFile(
        uploadForm("inputFile"),
        '_label -> "Queries"
    )
}
  1. What is the best way to validate inputFile?
  2. Is it possible do to that with annotations?

@Required constraint does not work at all.

I want it to be selected + add some limitation on size.

Upvotes: 1

Views: 2973

Answers (2)

Justus
Justus

Reputation: 33

Something like the following, maybe?

MultipartFormData body = request().body().asMultipartFormData();
if (!body.getFiles().isEmpty()) { 
  // do your work
}

Upvotes: 0

Ahmed Aswani
Ahmed Aswani

Reputation: 8659

make your form like:

 <input type="file" name="inputFile">

In you submit method add this:

 // from official documentation
    public static Result submit() {
      MultipartFormData body = request().body().asMultipartFormData();
      FilePart file = body.getFile("inputFile");
      if (inputFile != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType(); 
        File file = picture.getFile();
        // method the check size
        if(!validateFileSize){
          return redirect(routes.Application.index());    // error in file size 
        }
        return ok("File uploaded");
      } else {
        // here comes the validation
        flash("error", "Missing file");
        return redirect(routes.Application.index());    
      }
    }

Upvotes: 1

Related Questions