使用MultipartFile的多个文件上传在Spring Boot中不起作用,从JSP在Controller中获取空数组

时间:2018-06-19 12:26:28

标签: java spring spring-mvc spring-boot file-upload

我正在使用MultipartFile上传多个文件。但是从Jsp页面中,当我选择多个文件并单击Submit时,控制器中会出现空数组。

这是我的代码段,

在pom.xml中

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency> 

CommonsMultipartResolver Bean配置。

     @Bean
      public CommonsMultipartResolver multipartResolver() {
          CommonsMultipartResolver resolver=new CommonsMultipartResolver();
          resolver.setDefaultEncoding("utf-8");
          resolver.setMaxUploadSize(999999999);
          return resolver;
      }

JSP代码

<form:form method="POST" action="/createRequest"
        enctype="multipart/form-data">
        <input type="file" name="fileUpload" multiple />
        <br>
        <br><br>
        Select User
        <select name="userDirectory">
            <c:forEach items="${userslist}" var="user">
                <option value=${user.userDirectory}>${user.userName}</option>
            </c:forEach>

        </select>

        <input type="submit" value="Upload Files">
    </form:form>

控制器代码

@PostMapping(value = "/createRequest")
    public ModelAndView createRequest(@RequestParam("fileUpload") MultipartFile[] fileUpload,
            @RequestParam("userDirectory") String userDirectory) throws IOException {

        log.info("In createRequest method");
        if (fileUpload != null && fileUpload.length > 0) {
            Flow not coming here because fileUpload.length coming zero.
        }
        return new ModelAndView("success");
    }

在控制器fileUpload.length从JSP页面开始为零。  谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

private void initMultipartResolver(ApplicationContext context)
  {
    try
    {
      this.multipartResolver = ((MultipartResolver)context.getBean("multipartResolver", MultipartResolver.class));
      if (this.logger.isDebugEnabled()) {
        this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
      }
    }
    catch (NoSuchBeanDefinitionException ex)
    {
      this.multipartResolver = null;
      if (this.logger.isDebugEnabled())
        this.logger.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided");
    }
  }

使用此配置添加此配置后,任何enctype为multipart / form-data的请求都将在传递给Controller类之前由multipartResolver处理。