注:下面工具类主要用于对图片和视频进行校验,所抛出异常为作者自己声明的异常,此处可以根据自己业务情况,进行声明
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.getContentType().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.getContentType().toLowerCase()).find();
return flag;
}
/**
* 判断文件大小
*
* @param len 文件长度
* @param size 限制大小
* @param unit 限制单位(B,K,M,G)
* @return boolean
* @Description
* @author fuxshen
* @date 2022-10-10 11:47:36
**/
public static boolean checkFileSize(Long len, int size, String unit) {
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
}