Files
UserhomeService/src/main/java/com/yunhai/userhome/utils/FileUtil.java
T
chenxing a7539a4cf0
build / build-push (push) Successful in 1m3s
更新数字基座
2026-08-24 09:29:31 +08:00

71 lines
2.2 KiB
Java

package com.yunhai.userhome.utils;
import cn.hutool.core.util.IdUtil;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
/**
* File工具类(对齐旧 UserHome utils.FileUtil,仅保留 uploadImg 方法——本期迁移实际使用的唯一方法)。
*/
public class FileUtil {
/**
* 上传图片(byte[] 版),返回生成的文件名。
*/
public static String uploadImg(byte[] imgData, String pathName) {
String imgName = null;
String path = null;
File floorFile = null;
try {
for (int i = 0; i < 100; i++) {
imgName = UUID.randomUUID().toString().substring(0, 8) + ".png";
path = pathName + imgName;
floorFile = new File(path);
if (floorFile.exists()) continue;
else break;
}
FileOutputStream fos = new FileOutputStream(floorFile);
fos.write(imgData);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imgName;
}
/**
* 上传图片(MultipartFile 版),保留原始扩展名,返回生成的文件名。
*/
public static String uploadImg(MultipartFile file, String pathName) {
String imgName = null;
String path = null;
File floorFile = null;
try {
byte[] imgData = file.getBytes();
String fileName = file.getOriginalFilename();
int index = fileName.lastIndexOf(".");
String ext = "";
if (index > 0) {
ext = fileName.substring(index);
}
for (int i = 0; i < 100; i++) {
imgName = UUID.randomUUID().toString().substring(0, 8) + ext;
path = pathName + imgName;
floorFile = new File(path);
if (floorFile.exists()) continue;
else break;
}
FileOutputStream fos = new FileOutputStream(floorFile);
fos.write(imgData);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imgName;
}
}