Files
tiesheng-springboot/springboot-util/src/main/java/com/tiesheng/util/pojos/FileUploadPath.java
2023-01-11 14:40:27 +08:00

135 lines
3.3 KiB
Java

package com.tiesheng.util.pojos;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
public class FileUploadPath {
public static String UPLOAD_FOLDER = "/upload/";
/**
* 绝对路径
*/
private String absolutePath;
/**
* 访问路径
*/
private String httpPath;
private FileUploadPath() {
}
/**
* 获得一个文件路径
*
* @param fileName
* @return
*/
public static FileUploadPath get(String fileName) {
// 下载文件
fileName = downloadFile(fileName);
FileUploadPath pathBean = new FileUploadPath();
String tempPath = fileName;
if (!StrUtil.startWith(tempPath, UPLOAD_FOLDER)) {
tempPath = UPLOAD_FOLDER + DateUtil.format(DateUtil.date(), "yyyy-MM") + "/" + fileName;
}
pathBean.setHttpPath(tempPath);
pathBean.setAbsolutePath(String.format("%s/static%s", System.getProperty("user.dir"), tempPath));
FileUtil.mkParentDirs(pathBean.getAbsolutePath());
return pathBean;
}
/**
* 下载http文件
*
* @param fileName
* @return
*/
public static String downloadFile(String fileName) {
if (!StrUtil.startWith(fileName, "http")) {
return fileName;
}
String newFileName = UPLOAD_FOLDER + StrUtil.subAfter(fileName, UPLOAD_FOLDER, true);
FileUploadPath uploadPath = get(newFileName);
if (!FileUtil.exist(uploadPath.getAbsolutePath())) {
HttpUtil.downloadFile(fileName, uploadPath.getAbsolutePath());
}
return uploadPath.getHttpPath();
}
/**
* 随机生成一个文件路径
*
* @return
*/
public static FileUploadPath random() {
return get(IdUtil.simpleUUID());
}
/**
* 随机生成一个文件路径
*
* @return
*/
public static FileUploadPath random(String fileExt) {
return get(IdUtil.simpleUUID() + "." + fileExt);
}
/**
* 获取一个目录
*
* @param folder
* @return
*/
public static FileUploadPath folder(String folder) {
FileUploadPath pathBean = new FileUploadPath();
String tempFolder = folder;
if (!StrUtil.startWith(tempFolder, UPLOAD_FOLDER)) {
tempFolder = UPLOAD_FOLDER + tempFolder;
}
if (!StrUtil.endWith(folder, "/")) {
tempFolder = tempFolder + "/";
}
pathBean.setHttpPath(tempFolder);
pathBean.setAbsolutePath(String.format("%s/static%s", System.getProperty("user.dir"), tempFolder));
FileUtil.mkParentDirs(pathBean.getAbsolutePath());
return pathBean;
}
///////////////////////////////////////////////////////////////////////////
// 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;
}
}