springmvc上传文件
必要步骤
- 前端form表单加入 enctype=“multipart/form-data” 属性
- pom引入 commons-fileupload 依赖(在maven库 https://mvnrepository.com/ 中搜索)
- servlet中配置 multipartResolver
- controller使用 MultipartFile 参数
1.form表单
<form action='${basePath}/test/uploadFile.do' method='post' enctype="multipart/form-data">
<input type="file">
<input type="submit">
</form>
2.依赖引入
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
3.servlet配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="4194304" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
4.controller
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/uploadFile")
public String uploadFile(MultipartFile multipartFile) {
String fileName = multipartFile.getOriginalFilename();
}
}