代码之家  ›  专栏  ›  技术社区  ›  MehdiB

没有选择时,thymeleaf多文件输入发送空文件

  •  0
  • MehdiB  · 技术社区  · 6 年前

    我在百里香有一个多文件输入:

    <div class="form-group">
        <label for="photos" class="control-label" th:text="#{projects.new.photos}">Photos</label>
        <input type="file" multiple="multiple" th:field="*{photos}" class="form-control" th:class=" ${#fields.hasErrors('photos')} ? 'form-control is-invalid' : 'form-control'" id="photos" name="photos" placeholder="Project Photos" th:placeholder="#{projects.new.photos.placeholder}">
        <div class="invalid-feedback" th:if="${#fields.hasErrors('photos')}" th:errors="*{photos}"> Error</div>
    </div>
    

    在我的验证器类中,我像这样检查字段:

    if(files.length == 0 && required==false) {
        return true;
    }
    

    该字段不是必需的,但是当我选择no files时,在我的spring boot应用程序中会得到一个包含一个项的文件数组。所以 files 上面代码段中的数组的长度为1,验证未按预期工作。 数组中的唯一项的contentType为application/octet stream,大小为-1。这是默认行为还是我做错了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Flocke    6 年前

    更新:

    我想我知道这是从哪里来的。文件类型的输入字段的行为与复选框类型的字段不同。表单提交键值对,即使未设置该值。因此,控制器接收这样的对,并且单键非值对由空的多部分对象(下文中称为“mp1”)表示。由于要将多部分文件对象数组定义为输入参数,spring将“mp1”映射到长度为1的数组。就这样。

    原始答案:

    我猜您正在使用org.springframework.web.multipart.multipartfile[]作为输入参数。我认为你应该检查一下存在/大小:

    int size = 0;
    for (MultipartFile file : files) 
    {
       if (file != null && !file.isEmpty()) size++;
    }
    

    我总是对multipart对象执行这个空的和额外的isempty检查,我想原因是我有时会得到一个没有内容的multipartfile对象。

    编辑:如果您至少使用Java 8,您可以使用这一行:

    boolean empty = 
      Arrays.asList(files).stream().filter(f -> !f.isEmpty()).count() == 0;