| | |
| | | package org.jeecg.common.util; |
| | | |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.apache.commons.lang3.StringUtils; |
| | | import org.jeecg.common.api.vo.FileUploadResult; |
| | | import org.jeecg.common.exception.ExceptionCast; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.*; |
| | | import java.net.URLEncoder; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Paths; |
| | | import java.util.ArrayList; |
| | | import java.util.Date; |
| | | import java.util.List; |
| | | |
| | | @Slf4j |
| | | @Component |
| | | public class FileUtil { |
| | | |
| | |
| | | return dto; |
| | | } |
| | | |
| | | public static FileUploadResult uploadFile(byte[] fileData, String fileName) { |
| | | String suffix = getFileSuffix(fileName); |
| | | Date currentDate = DateUtils.getDate(); |
| | | String monthStr = DateUtils.date2Str(currentDate, DateUtils.monthFormat.get()); |
| | | // 相对路径 |
| | | String relativePath = "/" + monthStr + "/" + DateUtils.getDayStr(currentDate) + "/"; |
| | | // 绝对路径 |
| | | String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtils.getDayStr(currentDate) + "/"; |
| | | String fileNameNonSuffix = getFilenameNonSuffix(fileName); |
| | | if (StringUtils.isBlank(fileNameNonSuffix)) { |
| | | return null; |
| | | } |
| | | // 获取文件加密名称 1 保证文件唯一 不存在覆盖问题 2 目录下保存文件加密名称 去除文件关键信息 |
| | | String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis()) + "." + suffix; |
| | | Long fileSize = (long) fileData.length; |
| | | try { |
| | | File targetFile = new File(absolutePath, encodeFileName); |
| | | if(!targetFile.getParentFile().exists()) { |
| | | //创建目录 |
| | | targetFile.getParentFile().mkdirs(); |
| | | } |
| | | Files.write(Paths.get(absolutePath + encodeFileName), fileData); |
| | | FileUploadResult dto = new FileUploadResult(); |
| | | dto.setFileName(fileNameNonSuffix); |
| | | dto.setFileEncodeName(encodeFileName); |
| | | dto.setFilePath(relativePath + encodeFileName); |
| | | dto.setFileSize(fileSize); |
| | | dto.setFileSuffix(suffix); |
| | | return dto; |
| | | } catch (IOException e) { |
| | | log.error("文件写入失败: {}", e.getMessage(), e); |
| | | return null; |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * @param filePath 路径 |
| | | * @param fileName 文件名 |