必填请求部分'文件'在Spring-boot中提交表单后不存在

时间:2017-09-06 09:39:31

标签: java spring-boot thymeleaf

在Spring上传一个包含输入类型文件的表单后,我得到一个异常,即缺少所请求的参数。 这是我的表格:

<form method="POST" th:action="@{/form}" enctype="multipart/form-data" role="form">
    <input type="file" name="file" onchange="this.form.submit()"/>
</form>

这是我的控制者:

@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file) throws IOException {
    if (!file.isEmpty()) {
        BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
        File destination = new File("directory");
        ImageIO.write(src, "png", destination);
        return "redirect:uploadSuccess";
    } else {
        return "redirect:uploadFailure";
    }
}

在pom.xml文件中,我添加了依赖项

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

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

在我的Application类中,我添加了bean(没有web.xml):

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

但是我得到了

There was an unexpected error (type=Bad Request, status=400).
Required request part 'file' is not present

为什么文件没有正确上传? 谢谢

1 个答案:

答案 0 :(得分:1)

将映射更改为:

@RequestMapping(value = "/form", method = RequestMethod.POST, consumes = "multipart/form-data") public String handleFormUpload(@RequestPart("file") MultipartFile file)