package cn.lili.utils;
|
|
import cn.lili.common.exception.FileFormatNotSupport;
|
import cn.lili.modules.lmk.domain.entity.LmkFile;
|
import cn.lili.modules.lmk.enums.general.FileTypeEnum;
|
import org.apache.commons.lang3.StringUtils;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import java.text.SimpleDateFormat;
|
import java.util.Date;
|
import java.util.Random;
|
|
/**
|
* @author 29443
|
* @version 1.0
|
* @date 2022/4/25
|
*/
|
public class FileUtil {
|
|
/**
|
* 获取文件后缀
|
*
|
* @param fileName
|
* @return
|
*/
|
public static String getSuffix(String fileName) {
|
String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
|
return suffix;
|
}
|
|
/**
|
* 获取该文件上传到oss哪个目录
|
*
|
* @param suffix 文件后缀
|
* @return
|
*/
|
public static String getFileType(String suffix) {
|
String fileType = "";
|
for (FileTypeEnum type : FileTypeEnum.values()) {
|
if (type.getSuffixs().contains(suffix)) {
|
fileType = type.getType();
|
return fileType;
|
}
|
}
|
if (StringUtils.isBlank(fileType)) {
|
throw new FileFormatNotSupport("文件格式" + suffix + "不支持", 500);
|
}
|
return fileType;
|
}
|
|
/**
|
* 获取文件的信息,调用此方法默认普通上传
|
*
|
* @param file
|
* @return
|
*/
|
public static LmkFile getFileInfo(MultipartFile file) {
|
String originalFilename = file.getOriginalFilename();
|
String random = generateFileKey();
|
String suffix = getSuffix(originalFilename);
|
String fileType = getFileType(suffix);
|
String fileKey = String.format("%s/%s.%s", fileType, random, suffix);
|
|
LmkFile fileInfo = new LmkFile();
|
fileInfo.setFileKey(fileKey);
|
fileInfo.setOriginalFileName(originalFilename);
|
fileInfo.setFileType(file.getContentType());
|
fileInfo.setFileSize(file.getSize());
|
|
return fileInfo;
|
}
|
|
|
/**
|
* 获取fileKey
|
*
|
* @return
|
*/
|
public static String generateFileKey() {
|
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
|
String no = format.format(new Date());
|
Random random = new Random();
|
for (int i = 0; i < 5; i++) {
|
no += random.nextInt(10);
|
}
|
return no;
|
}
|
|
}
|