准备
<!--图片压缩-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.14</version>
</dependency>
文件上传工具类
说明:
文件上传到服务器时,按照日期来存放文件。
工具类名称 FileUtils.java
/**
* 说明: 上传文件
* @author zhangxiaosan
* @create 2022/1/21
* @param file 文件对象
* @param savePath 文件保存的路径
* @return
*/
public static Map<String,String> fileUpload(MultipartFile file, String savePath) throws Exception{
// 创建文件夹
String path = FileUtil.createPath(savePath);
BufferedOutputStream stream = null;
byte[] bytes = file.getBytes();
//获取文件名
String fileName = file.getOriginalFilename().toLowerCase();
//获取文件后缀名
String type = FileUtil.getFileTypeByPath(fileName);
String uuidName = UUID.randomUUID().toString();
fileName = uuidName + "." + type; // 新的文件名称uuid.type prefix
String filePath = path + File.separator + fileName;
File file1 = new File(filePath);//创建文件
int i = 1;
while (file1.exists()) {
fileName = uuidName + "_" + i + "." + type;
filePath = savePath + fileName;
file1 = new File(filePath);
i++;
}
stream = new BufferedOutputStream(new FileOutputStream(file1));
stream.write(bytes);// 写入
stream.close();
//图片压缩
Thumbnails.of(file1)
.scale(1f)
.outputQuality(0.25f)
.outputFormat(type)
.toFile(filePath);// 图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量
Map<String,String> resMap = new HashMap<String,String>();
resMap.put("fileName",uuidName);
resMap.put("fileType",type);
resMap.put("filePath",filePath);
resMap.put("dirPath",path);
return resMap;
}
/**
* 说明: 以当前时间在指定路径生成文件夹,文件夹格式 yyyyMMdd
* @author zhangxiaosan
* @create 2022/1/21
* @param savePath 文件夹路径
* @return 文件夹路径
*/
public static String createPath(String savePath){
return createPath(savePath, null);
}
/**
* 说明: 以当前时间在指定路径生成文件夹,自定义文件夹格式
* @author zhangxiaosan
* @create 2022/1/21
* @param savePath 文件夹路径
* @param format 文件夹格式,只能支持时间格式 默认格式为:yyyyMMdd
* @return 文件夹路径
*/
public static String createPath(String savePath,String format){
// 以当前日期创建存放文件的文件夹,不存在文件夹则创建
String setFormat = StringUtil.isEmpty(format)==true? "yyyyMMdd" : format ;
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern(setFormat));
File fileDir = new File(savePath + now);
if (!fileDir.exists()) fileDir.mkdirs();
return savePath + now;
}
/**
* 说明: 根据文件路径或文件名获取文件后缀名
* @author zhangxiaosan
* @create 2022/1/21
* @param path 文件路径或文件名
* @return
*/
public static String getFileTypeByPath(String path){
//获取最后一个.的位置
int lastIndexOf = path.lastIndexOf(".");
//获取文件的后缀名 .jpg
String type = path.substring(lastIndexOf + 1);
return type;
}