前端控制器
@PostMapping("/upload")
public ApiDto.Responseup(MultipartFile certificationImg) {
String msg = ImageUtil.imageProcessing(certificationImg);
return ApiDto.Response.success(msg);
}
业务层
public class ImageUtil {
public static StringimageProcessing(MultipartFile certificationImg) {
//图片类型校验
String filename = certificationImg.getOriginalFilename().toLowerCase();
if (!filename.matches("^.+\\.(png|jpg|gif)$")) {
return "上传照片格式错误";
}
try {
BufferedImage bi = ImageIO.read(certificationImg.getInputStream());
Integer width = bi.getWidth();
Integer height = bi.getHeight();
if (width==0||height==0) {
return "上传的照片有误,请检查重试";
}
}catch (Exception e) {
e.printStackTrace();
return "上传的照片有误,请检查重试";
}
//生成图片存储目录
String dateDir;
dateDir =new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
String path="";
try {
//String uploadDir= ResourceUtils.getURL("classpath:").getPath()+"resources/imgs/";
String uploadDir="resources/";
path = uploadDir + dateDir;
//指定文件目录
File dir =new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
}catch (Exception e){
e.printStackTrace();
return "文件目录异常";
}
//随机生成图片名
String uuid = UUID.randomUUID().toString();
String fileType = filename.substring(filename.lastIndexOf("."));
String realFileName = uuid + fileType;
String realPath = path + realFileName;
System.out.println(realPath);
//上传图片
File file =new File(realPath);
try {
//第一种写法,无法很好的支持动态路径
//certificationImg.transferTo(file);
//第二种写法,本质上还是上传后复制,会占用两次空间
// FileUtils.copyInputStreamToFile(certificationImg.getInputStream(), file);
//第三种写法,直接写入
byte[] bytes = certificationImg.getBytes();
Path rpath = Paths.get(realPath);
Files.write(rpath,bytes);
}catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return realPath;
}
}