注:下面工具类主要用于对图片和视频格式进行校验,所抛出异常为作者自己声明的异常,此处可以根据自己业务情况,进行声明
public class ImageUtils {
/**
* 图片校验(上传单个图片)
*
* @param file
* @return void
* @Description
* @author fuxshen
* @date 2022-04-29 08:58:17
**/
public static void checkImage(MultipartFile file) {
if (ObjectUtils.isEmpty(file) || file.getSize() <= 0) {
throw new ServiceException("上传内容为空");
}
if (!imageCheck(file)) {
throw new ServiceException("请上传图片格式为【jpg、png、tiff、webp、heif、gif、bmp】");
}
}
/**
* 图片和视频校验(上传多个)
*
* @param file
* @return void
* @Description
* @author fuxshen
* @date 2022-04-29 14:52:12
**/
public static void checkHomeImage(MultipartFile[] file) {
if (ObjectUtils.isEmpty(file)) {
throw new ServiceException("上传内容为空");
}
for (MultipartFile multipartFile : file) {
if (imageCheck(multipartFile)){
if (!imageCheck(multipartFile)) {
throw new ServiceException("请上传图片格式为【jpg、png、tiff、webp、heif、gif、bmp】");
}
}
if (videoCheck(multipartFile)){
if (!videoCheck(multipartFile)) {
throw new ServiceException("请上传正确视频格式为【mp4、flv、avi、mov、rm、rmvb、wmv、hevc】");
}
}
}
}
/**
* 校验视频的正则
*
* @param file
* @return boolean
* @Description
* @author fuxshen
* @date 2022-04-29 15:08:06
**/
public static boolean videoCheck(MultipartFile file) {
String reg = "(mp4|flv|avi|mov|rm|rmvb|wmv|hevc)";
Pattern pattern = Pattern.compile(reg);
boolean flag = pattern.matcher(file.getOriginalFilename().toLowerCase()).find();
return flag;
}
/**
* 图片校验正则
*
* @param file
* @return boolean
* @Description
* @author fuxshen
* @date 2022-04-29 15:25:31
**/
public static boolean imageCheck(MultipartFile file) {
String reg = "(jpg|png|tiff|webp|heif|gif|bmp)";
Pattern pattern = Pattern.compile(reg);
boolean flag = pattern.matcher(file.getOriginalFilename().toLowerCase()).find();
return flag;
}