@@ -1,11 +1,17 @@
|
||||
package com.yunhai.userhome.utils;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
@@ -13,6 +19,9 @@ import java.util.UUID;
|
||||
*/
|
||||
public class FileUtil {
|
||||
|
||||
/** 允许上传的图片扩展名(与前端 accept 对齐,含 icon 场景的 svg) */
|
||||
private static final Set<String> ALLOWED_EXT = new HashSet<>(Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"));
|
||||
|
||||
/**
|
||||
* 上传图片(byte[] 版),返回生成的文件名。
|
||||
*/
|
||||
@@ -32,13 +41,14 @@ public class FileUtil {
|
||||
fos.write(imgData);
|
||||
fos.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new BizException(ErrorCode.INTERNAL_SERVER_ERROR, "上传失败");
|
||||
}
|
||||
return imgName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片(MultipartFile 版),保留原始扩展名,返回生成的文件名。
|
||||
* <p>扩展名不在白名单内抛 {@link BizException}(服务端校验,防绕过前端 accept)。</p>
|
||||
*/
|
||||
public static String uploadImg(MultipartFile file, String pathName) {
|
||||
String imgName = null;
|
||||
@@ -50,7 +60,10 @@ public class FileUtil {
|
||||
int index = fileName.lastIndexOf(".");
|
||||
String ext = "";
|
||||
if (index > 0) {
|
||||
ext = fileName.substring(index);
|
||||
ext = fileName.substring(index).toLowerCase(Locale.ROOT);
|
||||
}
|
||||
if (!ALLOWED_EXT.contains(ext)) {
|
||||
throw new BizException(ErrorCode.CUSTOM, "不支持的图片格式");
|
||||
}
|
||||
for (int i = 0; i < 100; i++) {
|
||||
imgName = UUID.randomUUID().toString().substring(0, 8) + ext;
|
||||
@@ -63,8 +76,23 @@ public class FileUtil {
|
||||
fos.write(imgData);
|
||||
fos.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new BizException(ErrorCode.INTERNAL_SERVER_ERROR, "上传失败");
|
||||
}
|
||||
return imgName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除上传的物理文件(按 /upload/ 相对 URL 还原路径)。
|
||||
* <p>非本地上传(完整 URL / 跨仓地址)或文件不存在时静默跳过。</p>
|
||||
*/
|
||||
public static void deleteFile(String basePath, String relativeUrl) {
|
||||
if (relativeUrl == null || relativeUrl.isEmpty() || !relativeUrl.startsWith("/upload/")) {
|
||||
return;
|
||||
}
|
||||
String rel = relativeUrl.substring("/upload/".length());
|
||||
File file = new File(basePath, rel);
|
||||
if (file.exists()) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user