1、先写好controller类,有两个方法,getUploadPage()方法是接收请求,跳转到upload.html页面,upload(@RequestParam("file") MultipartFile file)方法,处理上传的文件
@Controller
public class HomeController {
@Value("${uploadPath}")
private String uploadPath;
@RequestMapping(value="/getUpload",method = RequestMethod.GET)
public String getUploadPage(){
return "/upload";
}
@RequestMapping(value="/upload",method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws IOException{
System.out.println("上传文件:"+file.getOriginalFilename());
String filePath = uploadPath + file.getOriginalFilename();
file.transferTo(new File(filePath));
return "/yes";
}
}
2、upload.html页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>springboot上传例子</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
3、上传文件大小及地址的设置
spring.http.multipart.maxFileSize = 1024Mb
spring.http.multipart.maxRequestSize = 1024Mb
uploadPath=F:/
4、连接重置的设置
@Configuration
public class MyConfig {
//Tomcat large file upload connection reset
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
如果不设置,会报如下错误:
文章参考:纯洁的微笑 http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html
替大佬(一位很有意思的大佬)打个广告,欢迎关注大佬的公众号