Springboot上传文件
文件上传三要素:
1、html文件表单项类型:type="file"
2、html文件表单提交方式:post
3、html文件enctype属性为多部分表单形式,即enctype="multipart/form-data"
文件上传所需依赖:
1、导入commons-fileupload依赖
2、配置上传解析器(springboot在application.properties文件配置)
3、编写文件上传代码
单文件上传代码:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) {
//判断文件是否为空,空则返回失败页面
if (file.isEmpty()) {
return "index";
}
// 获取原文件名
String filename = file.getOriginalFilename();
String filePath = "C:/Users/Administrator/Desktop/";
// 创建文件实例
File dest = new File(filePath + filename);
try {
// 写入文件
file.transferTo(dest);
LOGGER.info("上传成功");
return "index";
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
return "index";
}
多文件上传代码:
@RequestMapping(value = "uploads",method = RequestMethod.POST)
public String uploads(@RequestParam("files") MultipartFile[] files) throws IOException {
for (MultipartFile multipartFile : files) {
//获取原文件名
String filename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("C:/Users/Administrator/Desktop/" + filename));
}
return "index";
}
文件上传超出大小限制解决:(全局异常处理类)
缺点:编写大量的异常处理方法,代码冗余
@ControllerAdvice//controller增强器,用来捕获controller里的异常
public class GlobalExceptionHandler {
//slf4j日志
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* @return 该方法需要返回一个 ModelAndView:目的是可以让我们封装异常信息以及视图的指定
* 参数 Exception e:会将产生异常对象注入到方法中
* @Description: 文件上传过大异常
* RedirectAttributes 转发功能
*/
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView processException(MaxUploadSizeExceededException e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message","上传文件大小超出限制!");
modelAndView.setViewName("file/upload");
LOGGER.error("最大上传文件为10M,上传文件大小超出限制!");
return modelAndView;
}
}
注意:上传文件大小出现连接重置的问题,此异常内容 GlobalException 也捕获不到
@Bean
public TomcatServletWebServerFactory tomcatEmbedded() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
拓展:设置文件大小限制
1)入口类添加
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//设置文件大小限制,超过设置大小,则页面会抛出异常信息
factory.setMaxFileSize("10MB");
//设置上传数据总大小
factory.setMaxRequestSize("10MB");
//创建一个上传配置
return factory.createMultipartConfig();
}
2)配置文件application.properties
最大支持请求大小 spring.servlet.multipart.max-request-size=10MB
最大支持文件大小 spring.servlet.multipart.max-file-size=10MB