gpt4 book ai didi

java - Spring MVC 文件上传 : Unable to process parts as no multi-part configuration has been provided

转载 作者:行者123 更新时间:2023-11-29 04:39:35 26 4
gpt4 key购买 nike

我正在尝试使用 Spring MVC 和 Thymeleaf 上传文件,但出现异常,提示未提供多部分配置。

这是我的 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>

这是我的表单绑定(bind)类:

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

关于java - Spring MVC 文件上传 : Unable to process parts as no multi-part configuration has been provided,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39777391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com