1

我有一个简单的bean,像这样:

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;
}

和形式,像这样:

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

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

    @inputFile(
        uploadForm("inputFile"),
        '_label -> "Queries"
    )
}
  1. 验证 inputFile 的最佳方法是什么?
  2. 是否可以通过注释来做到这一点?

@Required constraint根本不起作用。

我希望它被选中+添加一些大小限制。

4

2 回答 2

1

使您的表格如下:

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

在您提交方法中添加:

 // 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());    
      }
    }
于 2012-04-30T07:52:11.457 回答
0

像下面这样的东西,也许?

MultipartFormData body = request().body().asMultipartFormData();
if (!body.getFiles().isEmpty()) { 
  // do your work
}
于 2012-08-22T13:50:13.223 回答