1. 需求: 文件上传的时候,需要根据图片或者视频校验尺寸比例和大小是否符合要求
2. 代码
2.1 前期准备
2.1.1. 需要的jar包
- maven仓库没有这个jar包,需要从网上下载,导入本地
链接:https://www.aliyundrive.com/s/enXJZnujTGf
- 在项目根目录新建 lib 文件夹,把jar包放入该文件夹
2.1.2. maven配置
导入依赖
<!-- 获取视频文件信息的jar-->
<dependency>
<groupId>it.sauronsoftware</groupId>
<artifactId>jave</artifactId>
<version>1.0.2</version>
<scope>system</scope>
<systemPath>/${project.basedir}/lib/jave-1.0.2.jar</systemPath>
</dependency>
<!-- 需要额外用到的工具类 hutool 工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.8</version>
</dependency>
2.2 代码
@Override
public String uploadFile(MultipartFile multipartFile, String type) throws IOException {
String result = null;
String filename = multipartFile.getOriginalFilename();
//把文件流复制到本地 或者把MultipartFile 转file
File file = new File(localDirectory + filename);
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
InputStream inputStream = null;
Double height = 0.0;
Double width = 0.0;
long kbSize;
long duration = 0;
// type 1: 图片 2: icon 3=视频
if ("1".equals(type)) {
/*
校验图片
宽高比例:9:16、16:9;大小不超过300KB ; 格式:png、jpg、jpeg
*/
inputStream = new FileInputStream(file);
BufferedImage image = ImageIO.read(inputStream);
height = (double) image.getHeight();
width = (double) image.getWidth();
kbSize = cn.hutool.core.io.FileUtil.size(file) / 1024;
if (!isImage(filename)) {
result = "请上传格式为png、jpg、jpeg的图片!";
}
} else if ("2".equals(type)) {
/*
校验icon
200x200以内,大小不超过200KB,格式:png、jpg、jpeg
*/
inputStream = new FileInputStream(file);
BufferedImage image = ImageIO.read(inputStream);
height = (double) image.getHeight();
width = (double) image.getWidth();
kbSize = cn.hutool.core.io.FileUtil.size(file) / 1024;
if (!isImage(filename)) {
result = "请上传格式为png、jpg、jpeg的图片!";
}
} else {
/*
校验视频
宽高比例:9:16、16:9,大小<=10M,5s<=时长格式<=30s,支持4g
*/
Encoder encoder = new Encoder();
MultimediaInfo m = encoder.getInfo(file);
height = (double) m.getVideo().getSize().getHeight();
width = (double) m.getVideo().getSize().getWidth();
//时长 秒
duration = m.getDuration() / 1000;
kbSize = cn.hutool.core.io.FileUtil.size(file) / 1024 ;
if (!isVideo(filename)) {
result = "请上传视频格式的文件!";
}
}
}
private Boolean isImage(String fileName) {
String reg = "(jpg|jpeg|png)";
Pattern p = Pattern.compile(reg);
return p.matcher(fileName).find();
}
private boolean isVideo(String fileName) {
String reg = "(mp4|flv|avi|rm|rmvb|wmv)";
Pattern p = Pattern.compile(reg);
boolean boo = p.matcher(fileName).find();
return boo;
}