前端上传表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="header_img"/>
<input type="submit" value="上传" />
</form>
</body>
</html>
后端接口
@RequestMapping(value="/upload")
public String upload(@RequestParam("header_img") MultipartFile file,HttpServletRequest request){
System.out.println("文件名称"+file.getOriginalFilename());
System.out.println("文件类型"+file.getContentType());
System.out.println("文件大小"+file.getSize());
//获取文件名称
String fileName = file.getOriginalFilename();
//获取文件后缀名称
String suffixNmae = fileName.substring(fileName.lastIndexOf("."));
//转换名称 方舟文件名称冲突
fileName = UUID.randomUUID()+suffixNmae;
System.out.println("转换后的文件名称"+fileName);
File data = new File(filePath + fileName);
try {
file.transferTo(data);
}catch ( IllegalStateException e){
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException(e);
}
return "1";
}
限制图片大小
- 不做任何处理的情况下,我上传一个2M左右的图片
- 在@SpringBootApplication 下加入拦截
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize(DataSize.parse("10240KB")); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize(DataSize.parse("1024000KB"));
return factory.createMultipartConfig();
}