本文最后更新于
2024-05-06,距今已有 388
天,若文章内容或图片链接失效,请留言反馈。
文件后缀名限定
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
String edward = FileUploadUtils.getExtension(file).toLowerCase();
String[] args = {"png", "gif", "jpeg", "jpg"};
Arrays.sort(args);
int result = Arrays.binarySearch(args, edward);
if (result < 0) {
throw new BadRequestException("上传的文件格式不支持,请重新选择!");
}
文件大小限定
if(!FileUploadUtils.fileSize(file.getSize(),5,"M")){
throw new BadRequestException("出错了!请上传png、gif、JPEG等格式,大小不超过5M的图片!");
}
实现工具类
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
public class FileUploadUtils {
public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
public static final String getExtension(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (StringUtils.isEmpty(extension)) {
extension = MimeTypeUtils.getExtension(file.getContentType());
}
return extension;
}
public static boolean fileSize(Long len, int size, String unit){
double fileSize = 0;
if ("B".equalsIgnoreCase(unit)) {
fileSize = (double) len;
} else if ("K".equalsIgnoreCase(unit)) {
fileSize = (double) len / 1024;
} else if ("M".equalsIgnoreCase(unit)) {
fileSize = (double) len / 1048576;
} else if ("G".equalsIgnoreCase(unit)) {
fileSize = (double) len / 1073741824;
}
return !(fileSize > size);
}
}