我正在尝试使用Spring MVC和Thymeleaf上载文件,但是我收到一个例外,说未提供多部分配置。

这是我的胸腺单:

<form action="#" th:action="@{/settings/profile}"
    th:object="${profileSettingsForm}" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <label for="profilePicture">Picture</label> <input type="file"
            th:field="*{profilePicture}" id="profilePicture" name="profilePicture">
    </div>
    <div class="form-group">
        <label for="username">Username</label> <input type="text"
            th:field="*{username}" class="form-control" id="username"
            placeholder="Type your new username">
    </div>
    <div class="form-group">
        <label for="biography">Biography</label>
        <textarea th:field="*{biography}" class="form-control" id="biography"
            rows="3" placeholder="Type your new biography"></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>


这是我的表单绑定类:

public class ProfileSettingsForm {

    private static final String NOT_BLANK_MESSAGE = "{notBlank.message}";

    private MultipartFile profilePicture;

    @NotBlank(message = ProfileSettingsForm.NOT_BLANK_MESSAGE)
    private String username;

    @NotBlank(message = ProfileSettingsForm.NOT_BLANK_MESSAGE)
    private String biography;

    public ProfileSettingsForm() {

    }

    public ProfileSettingsForm(String username, String biography) {
        this.username = username;
        this.biography = biography;
    }

    // Getters and setters

}


另外,我已经按照文档在WebMvcConfig.java中的说明配置了Multipart解析器,如下所示:

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


为什么即使设置了MultiPartResolver,上传表单也无法正常工作?我想念什么吗?

最佳答案

从没有发现多部分配置的例外出发,很简单。尽管您提供了multipartResolver bean。

问题在于,在Spring Security过滤器之前指定MultipartFilter时,它尝试获取multipartResolver bean,但找不到它。因为它期望bean名称/ id为filterMultipartResolver而不是multipartResolver。

帮个忙。请按如下所示更改Bean配置-

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


要么

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

07-24 09:24