问题描述
提示:CommonsMultipartFile cannot be resolved to a type
在新的 Spring6 中,官方删除了之前上传文件使用的 CommonsMultipartResolver 类,导致之前的上传文件方法行不通了。
解决方案
在 web.xml
文件配置前端处理器 DispatcherServlet
的标签中添加下面的配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- 配置文件上传的处理器 -->
<multipart-config>
<!-- 上传文件最大为多少 -->
<max-file-size>10485760</max-file-size>
<!-- 最大的请求大小 -->
<max-request-size>10485760</max-request-size>
<!-- 多大以上的文件可以上传 -->
<file-size-threshold>0</file-size-threshold>
</multipart-config>
</servlet>
|
接着在 Spring 的配置文件中,把 org.springframework.web.multipart.commons.CommonsMultipartyResolver
替换成 org.springframework.web.multipart.support.StandardServletMultipartResolver
1
2
|
<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartyResolver"/> -->
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
|
最后在 Controller
类的方法中,MultipartFile
类型的形参前面加上 @RequestParam
注解,注意别忘了 value
属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("message", "Please select a file to upload");
System.out.println("Please select a file to upload");
return "uploadStatus";
}
try {
// 保存文件到本地
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
// 把文件名添加到模型中
model.addAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
System.out.println("You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "uploadStatus";
}
|