准备文件上传工具类
准备文件上传工具类net.coobird thumbnailator 0.4.14
说明:
文件上传到服务器时,按照日期来存放文件。
工具类名称 FileUtils.java
public static Map 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 resMap = new HashMap();
resMap.put("fileName",uuidName);
resMap.put("fileType",type);
resMap.put("filePath",filePath);
resMap.put("dirPath",path);
return resMap;
}
public static String createPath(String savePath){
return createPath(savePath, null);
}
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;
}
public static String getFileTypeByPath(String path){
//获取最后一个.的位置
int lastIndexOf = path.lastIndexOf(".");
//获取文件的后缀名 .jpg
String type = path.substring(lastIndexOf + 1);
return type;
}



