Files
tiesheng-springboot/springboot-util/src/main/java/com/tiesheng/util/pojos/FileUploadPath.java
2023-03-14 14:03:53 +08:00

127 lines
3.1 KiB
Java

package com.tiesheng.util.pojos;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.tiesheng.util.config.GlobalConfig;
public class FileUploadPath {
public static String UPLOAD_FOLDER = "/upload/";
/**
* 绝对路径
*/
private String absolutePath;
/**
* 访问路径
*/
private String httpPath;
private FileUploadPath() {
}
/**
* 获得一个文件路径
*
* @param fileName
* @return
*/
public static FileUploadPath file(String fileName) {
// 下载文件
fileName = fileDownload(fileName);
FileUploadPath pathBean = new FileUploadPath();
String tempPath = fileName;
if (!StrUtil.startWith(tempPath, CharUtil.SLASH)) {
tempPath = CharUtil.SLASH + tempPath;
}
if (!StrUtil.startWith(tempPath, UPLOAD_FOLDER)) {
tempPath = UPLOAD_FOLDER + DateUtil.format(DateUtil.date(), "yyyy-MM") + CharUtil.SLASH + fileName;
}
pathBean.setHttpPath(tempPath);
String tempAbs = String.format("%s/static%s", SpringUtil.getBean(GlobalConfig.class).getUploadDir(), tempPath);
tempAbs = FileUtil.normalize(tempAbs);
pathBean.setAbsolutePath(tempAbs);
FileUtil.mkParentDirs(pathBean.getAbsolutePath());
return pathBean;
}
/**
* 下载http文件
*
* @param httpUrl
* @return
*/
public static String fileDownload(String httpUrl) {
if (!StrUtil.startWith(httpUrl, "http")) {
return httpUrl;
}
String newFileName = UPLOAD_FOLDER + StrUtil.subAfter(httpUrl, UPLOAD_FOLDER, true);
FileUploadPath uploadPath = file(newFileName);
if (!FileUtil.exist(uploadPath.getAbsolutePath())) {
HttpUtil.downloadFile(httpUrl, uploadPath.getAbsolutePath());
}
return uploadPath.getHttpPath();
}
/**
* 随机生成一个文件路径
*
* @return
*/
public static FileUploadPath random(String fileExt) {
String fileName = IdUtil.simpleUUID();
if (!StrUtil.isEmpty(fileExt)) {
fileName = fileName + "." + fileExt;
}
return file(fileName);
}
/**
* 获取一个目录
*
* @param folder
* @return
*/
public static FileUploadPath folder(String folder) {
FileUploadPath file = file(folder);
FileUtil.mkdir(file.getAbsolutePath());
return file;
}
///////////////////////////////////////////////////////////////////////////
// setter\getter
///////////////////////////////////////////////////////////////////////////
public String getAbsolutePath() {
return absolutePath;
}
public void setAbsolutePath(String absolutePath) {
this.absolutePath = absolutePath;
}
public String getHttpPath() {
return httpPath;
}
public void setHttpPath(String httpPath) {
this.httpPath = httpPath;
}
}