前端代码
要注意:
1、在form标签上加上enctype=“multipart/form-data”,不然会报类型不匹配错误
2、在input标签上加上multiple才可以同时上传多个文件
<form th:action="@{upload/image}" th:method="post" enctype="multipart/form-data">
<input th:type="file" name="file" multiple>
<input th:type="submit" th:value="提交">
</form>
后端代码
@RestController
@RequestMapping("upload")
public class UploadController {
private static final List<String> suffixes= Arrays.asList("multipart/form-data","image/png", "image/jpeg");
@PostMapping("image")
public ResponseEntity<String> uploadImage(@RequestParam("file")MultipartFile file){
System.out.println("正在进行图片上传。。。");
try {
//校验图片
//文件后缀名校验,这里是自定义几种类型
String type=file.getContentType();
if (!suffixes.contains(type)){
System.out.println("上传失败,文件类型不匹配");
return null;
}
BufferedImage image = ImageIO.read(file.getInputStream());
if (image==null){
return null;
}
// 随机名
UUID rid=UUID.randomUUID();
long uid = rid.getLeastSignificantBits();
// 获取文件上传名
String filename=file.getOriginalFilename();
// 获取文件上传后缀名
String suffix=filename.substring(filename.lastIndexOf("."));
// 方式一、直接使用上传文件的文件名
// File dest=new File("E:/test",filename);
// 方式二、使用自定义随机名
File dest=new File("E:/test/"+uid+suffix);
file.transferTo(dest);//这里经常会出现系统找不到指定路径,仔细查看本地路径
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(file.getOriginalFilename());
}