wip: 重构文件系统中

This commit is contained in:
ah--desktop
2026-01-18 23:46:01 +08:00
parent 0056f2bb11
commit 79109202d3
26 changed files with 1485 additions and 89 deletions
@@ -0,0 +1,52 @@
package top.xyquan.ecomdmbbackend.modules.sys.config;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 阿里云OSS配置
*/
@Configuration
public class OssConfig {
@Value("${oss.endpoint:}")
private String endpoint;
@Value("${oss.access-key-id:}")
private String accessKeyId;
@Value("${oss.access-key-secret:}")
private String accessKeySecret;
@Value("${oss.bucket-name:}")
private String bucketName;
@Value("${oss.domain:}")
private String domain;
@Bean
public OSS ossClient() {
if (endpoint == null || endpoint.isEmpty() ||
accessKeyId == null || accessKeyId.isEmpty() ||
accessKeySecret == null || accessKeySecret.isEmpty()) {
return null;
}
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
public String getEndpoint() {
return endpoint;
}
public String getBucketName() {
return bucketName;
}
public String getDomain() {
return domain;
}
}
@@ -0,0 +1,60 @@
package top.xyquan.ecomdmbbackend.modules.sys.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchCreateOssFileDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.BatchSignUrlVO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileVO;
import top.xyquan.ecomdmbbackend.modules.sys.service.SysFileService;
import java.util.List;
/**
* 系统文件管理控制器
*/
@Tag(name = "系统-文件管理", description = "文件上传和管理相关接口")
@RestController
@RequestMapping("/sys/file")
public class SysFileController {
private final SysFileService sysFileService;
public SysFileController(SysFileService sysFileService) {
this.sysFileService = sysFileService;
}
@Operation(summary = "批量上传文件", description = "批量上传文件到服务器(仅用于本地存储)")
@PostMapping("/batch-upload")
public ApiResponse<List<SysFileUploadVO>> batchUploadFiles(@RequestParam("files") List<MultipartFile> files) {
List<SysFileUploadVO> result = sysFileService.batchUploadFiles(files);
return ApiResponse.success(result);
}
@Operation(summary = "批量获取URL签名", description = "批量获取OSS文件上传URL签名,如果文件已存在则返回文件信息")
@PostMapping("/batch-sign-url")
public ApiResponse<BatchSignUrlVO> batchSignUrl(@Valid @RequestBody BatchSignUrlDTO dto) {
BatchSignUrlVO result = sysFileService.batchSignUrl(dto);
return ApiResponse.success(result);
}
@Operation(summary = "批量创建OSS文件记录", description = "前端上传OSS文件成功后,批量创建文件记录")
@PostMapping("/batch-create-oss")
public ApiResponse<List<SysFileVO>> batchCreateOssFiles(@Valid @RequestBody BatchCreateOssFileDTO dto) {
List<SysFileVO> result = sysFileService.batchCreateOssFiles(dto);
return ApiResponse.success(result);
}
@Operation(summary = "获取文件访问URL", description = "通过文件ID获取文件访问URL")
@GetMapping("/{fileId}/access-url")
public ApiResponse<String> getFileAccessUrl(@PathVariable Long fileId) {
String accessUrl = sysFileService.getFileAccessUrl(fileId);
return ApiResponse.success(accessUrl);
}
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.sys.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.sys.model.po.SysFilePO;
/**
* 系统文件Mapper接口
*/
@Mapper
public interface SysFileMapper extends BaseMapper<SysFilePO> {
}
@@ -0,0 +1,82 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.file;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量创建OSS文件记录DTO
*/
@Data
@Schema(description = "批量创建OSS文件记录DTO")
public class BatchCreateOssFileDTO {
/**
* 文件列表
*/
@Schema(description = "文件列表", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "文件列表不能为空")
private List<FileItem> files;
/**
* 文件项
*/
@Data
@Schema(description = "文件项")
public static class FileItem {
/**
* 文件名
*/
@Schema(description = "文件名", example = "example.jpg", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "文件名不能为空")
private String filename;
/**
* 文件哈希值
*/
@Schema(description = "文件哈希值", example = "abc123def456", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "文件哈希值不能为空")
private String fileHash;
/**
* 存储路径/Key
*/
@Schema(description = "存储路径/Key", example = "uploads/2024/01/abc123def456.jpg", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "存储路径不能为空")
private String storagePath;
/**
* 文件大小(字节)
*/
@Schema(description = "文件大小(字节)", example = "102400")
private Long fileSize;
/**
* MIME类型
*/
@Schema(description = "MIME类型", example = "image/jpeg")
private String mimeType;
/**
* 文件分类(可选)
*/
@Schema(description = "文件分类", example = "image")
private String category;
/**
* 标签(可选)
*/
@Schema(description = "标签", example = "logo,品牌")
private String tags;
/**
* 备注(可选)
*/
@Schema(description = "备注", example = "公司Logo")
private String remark;
}
}
@@ -0,0 +1,45 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.file;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量URL签名DTO
*/
@Data
@Schema(description = "批量URL签名DTO")
public class BatchSignUrlDTO {
/**
* 文件列表
*/
@Schema(description = "文件列表", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "文件列表不能为空")
private List<FileItem> files;
/**
* 文件项
*/
@Data
@Schema(description = "文件项")
public static class FileItem {
/**
* 文件名
*/
@Schema(description = "文件名", example = "example.jpg", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "文件名不能为空")
private String filename;
/**
* 文件哈希值
*/
@Schema(description = "文件哈希值", example = "abc123def456", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "文件哈希值不能为空")
private String fileHash;
}
}
@@ -0,0 +1,63 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.file;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量上传文件DTO
*/
@Data
@Schema(description = "批量上传文件DTO")
public class BatchUploadFileDTO {
/**
* 文件列表
*/
@Schema(description = "文件列表", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "文件列表不能为空")
private List<FileItem> files;
/**
* 文件项
*/
@Data
@Schema(description = "文件项")
public static class FileItem {
/**
* 文件名
*/
@Schema(description = "文件名", example = "example.jpg", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "文件名不能为空")
private String filename;
/**
* 文件哈希值
*/
@Schema(description = "文件哈希值", example = "abc123def456", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "文件哈希值不能为空")
private String fileHash;
/**
* 文件分类(可选)
*/
@Schema(description = "文件分类", example = "image")
private String category;
/**
* 标签(可选)
*/
@Schema(description = "标签", example = "logo,品牌")
private String tags;
/**
* 备注(可选)
*/
@Schema(description = "备注", example = "公司Logo")
private String remark;
}
}
@@ -0,0 +1,125 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 系统文件实体
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_file")
public class SysFilePO {
/**
* 文件ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 公司ID
*/
@TableField("company_id")
private Long companyId;
/**
* 存储类型(local-本地存储,oss-阿里云OSS,s3-AWS S3,qiniu-七牛云,cos-腾讯云COS)
*/
@TableField("storage_type")
private String storageType;
/**
* 存储路径/Key(本地存储为相对路径,对象存储为存储Key)
*/
@TableField("storage_path")
private String storagePath;
/**
* 原始文件名
*/
@TableField("filename")
private String filename;
/**
* 文件格式/扩展名,如 pdf/jpg/png/xlsx/doc/cad
*/
@TableField("file_format")
private String fileFormat;
/**
* MIME类型,如 image/jpeg, application/pdf
*/
@TableField("mime_type")
private String mimeType;
/**
* 文件大小(字节)
*/
@TableField("file_size")
private Long fileSize;
/**
* 文件哈希值(MD5/SHA256),用于去重
*/
@TableField("file_hash")
private String fileHash;
/**
* 文件分类(image-图片,avatar-头像,logo-Logo,document-文档,video-视频,audio-音频等)
*/
@TableField("category")
private String category;
/**
* 标签,逗号分隔
*/
@TableField("tags")
private String tags;
/**
* 文件描述/备注
*/
@TableField("remark")
private String remark;
/**
* 上传人ID
*/
@TableField("upload_by")
private Long uploadBy;
/**
* 上传时间
*/
@TableField(value = "upload_time", fill = FieldFill.INSERT)
private LocalDateTime uploadTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 更新人ID
*/
@TableField("update_by")
private Long updateBy;
/**
* 删除时间(软删除)
*/
@TableField("delete_time")
private LocalDateTime deleteTime;
/**
* 删除人ID
*/
@TableField("delete_by")
private Long deleteBy;
}
@@ -0,0 +1,46 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 批量URL签名响应VO
*/
@Data
@Schema(description = "批量URL签名响应VO")
public class BatchSignUrlVO {
@Schema(description = "文件信息列表")
private List<FileSignInfo> files;
/**
* 文件签名信息
*/
@Data
@Schema(description = "文件签名信息")
public static class FileSignInfo {
@Schema(description = "文件名", example = "example.jpg")
private String filename;
@Schema(description = "文件哈希值", example = "abc123def456")
private String fileHash;
@Schema(description = "文件ID(如果文件已存在)", example = "1")
private Long fileId;
@Schema(description = "是否已存在", example = "true")
private Boolean exists;
@Schema(description = "上传URL(如果文件不存在,用于前端上传)", example = "https://oss.example.com/upload?signature=xxx")
private String uploadUrl;
@Schema(description = "访问URL(如果文件已存在,临时签名URL)", example = "https://oss.example.com/file.jpg?signature=xxx")
private String accessUrl;
@Schema(description = "文件信息(如果文件已存在)")
private SysFileVO fileInfo;
}
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 文件上传响应VO(不包含敏感信息)
*/
@Data
@Schema(description = "文件上传响应VO")
public class SysFileUploadVO {
@Schema(description = "文件ID", example = "1")
private Long id;
@Schema(description = "存储类型", example = "local")
private String storageType;
@Schema(description = "存储路径/Key", example = "./uploads/2024/01/file.jpg")
private String storagePath;
@Schema(description = "原始文件名", example = "example.jpg")
private String filename;
@Schema(description = "文件格式", example = "jpg")
private String fileFormat;
@Schema(description = "MIME类型", example = "image/jpeg")
private String mimeType;
@Schema(description = "文件大小(字节)", example = "102400")
private Long fileSize;
@Schema(description = "文件哈希值", example = "abc123def456")
private String fileHash;
@Schema(description = "文件分类", example = "image")
private String category;
@Schema(description = "标签", example = "logo,品牌")
private String tags;
@Schema(description = "文件描述", example = "公司Logo")
private String remark;
@Schema(description = "访问URL(临时签名URL,仅OSS存储)", example = "https://example.com/file.jpg?signature=xxx")
private String accessUrl;
}
@@ -0,0 +1,66 @@
package top.xyquan.ecomdmbbackend.modules.sys.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 系统文件VO
*/
@Data
@Schema(description = "系统文件VO")
public class SysFileVO {
@Schema(description = "文件ID", example = "1")
private Long id;
@Schema(description = "公司ID", example = "1")
private Long companyId;
@Schema(description = "存储类型", example = "oss")
private String storageType;
@Schema(description = "存储路径/Key", example = "uploads/2024/01/file.jpg")
private String storagePath;
@Schema(description = "原始文件名", example = "example.jpg")
private String filename;
@Schema(description = "文件格式", example = "jpg")
private String fileFormat;
@Schema(description = "MIME类型", example = "image/jpeg")
private String mimeType;
@Schema(description = "文件大小(字节)", example = "102400")
private Long fileSize;
@Schema(description = "文件哈希值", example = "abc123def456")
private String fileHash;
@Schema(description = "文件分类", example = "image")
private String category;
@Schema(description = "标签", example = "logo,品牌")
private String tags;
@Schema(description = "文件描述", example = "公司Logo")
private String remark;
@Schema(description = "上传人ID", example = "1")
private Long uploadBy;
@Schema(description = "上传时间", example = "2024-01-01T10:00:00")
private LocalDateTime uploadTime;
@Schema(description = "更新时间", example = "2024-01-01T10:00:00")
private LocalDateTime updateTime;
@Schema(description = "更新人ID", example = "1")
private Long updateBy;
@Schema(description = "访问URL(临时签名URL)", example = "https://example.com/file.jpg?signature=xxx")
private String accessUrl;
}
@@ -0,0 +1,53 @@
package top.xyquan.ecomdmbbackend.modules.sys.service;
import java.io.InputStream;
/**
* OSS服务接口
*/
public interface OssService {
/**
* 生成上传URL(预签名URL)
*
* @param storagePath 存储路径/Key
* @param expirationMinutes 过期时间(分钟)
* @return 预签名URL
*/
String generateUploadUrl(String storagePath, int expirationMinutes);
/**
* 生成访问URL(预签名URL)
*
* @param storagePath 存储路径/Key
* @param expirationMinutes 过期时间(分钟)
* @return 预签名URL
*/
String generateAccessUrl(String storagePath, int expirationMinutes);
/**
* 上传文件到OSS
*
* @param storagePath 存储路径/Key
* @param inputStream 文件输入流
* @return 是否上传成功
*/
boolean uploadFile(String storagePath, InputStream inputStream);
/**
* 删除OSS文件
*
* @param storagePath 存储路径/Key
* @return 是否删除成功
*/
boolean deleteFile(String storagePath);
/**
* 检查文件是否存在
*
* @param storagePath 存储路径/Key
* @return 是否存在
*/
boolean fileExists(String storagePath);
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.sys.service;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchCreateOssFileDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.BatchSignUrlVO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileVO;
import java.util.List;
/**
* 系统文件服务接口
*/
public interface SysFileService {
/**
* 批量上传文件(仅用于本地存储)
*
* @param files 文件列表
* @return 文件信息列表(不包含敏感信息)
*/
List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files);
/**
* 批量获取URL签名(用于前端上传到OSS)
*
* @param dto 批量签名请求DTO
* @return 批量签名响应VO
*/
BatchSignUrlVO batchSignUrl(BatchSignUrlDTO dto);
/**
* 批量创建OSS文件记录(前端上传成功后调用)
*
* @param dto 批量创建OSS文件记录DTO
* @return 文件信息列表
*/
List<SysFileVO> batchCreateOssFiles(BatchCreateOssFileDTO dto);
/**
* 通过文件ID获取文件访问URL
*
* @param fileId 文件ID
* @return 文件访问URL
*/
String getFileAccessUrl(Long fileId);
}
@@ -0,0 +1,101 @@
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.sys.config.OssConfig;
import top.xyquan.ecomdmbbackend.modules.sys.service.OssService;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
/**
* OSS服务实现类
*/
@Service
public class OssServiceImpl implements OssService {
private final OssConfig ossConfig;
private OSS ossClient;
public OssServiceImpl(OssConfig ossConfig) {
this.ossConfig = ossConfig;
this.ossClient = ossConfig.ossClient();
}
@Override
public String generateUploadUrl(String storagePath, int expirationMinutes) {
if (ossClient == null) {
return null;
}
try {
Date expiration = new Date(System.currentTimeMillis() + expirationMinutes * 60 * 1000L);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
ossConfig.getBucketName(), storagePath);
request.setExpiration(expiration);
request.setMethod(com.aliyun.oss.HttpMethod.PUT);
URL url = ossClient.generatePresignedUrl(request);
return url.toString();
} catch (Exception e) {
return null;
}
}
@Override
public String generateAccessUrl(String storagePath, int expirationMinutes) {
if (ossClient == null) {
return null;
}
try {
Date expiration = new Date(System.currentTimeMillis() + expirationMinutes * 60 * 1000L);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
ossConfig.getBucketName(), storagePath);
request.setExpiration(expiration);
request.setMethod(com.aliyun.oss.HttpMethod.GET);
URL url = ossClient.generatePresignedUrl(request);
return url.toString();
} catch (Exception e) {
return null;
}
}
@Override
public boolean uploadFile(String storagePath, InputStream inputStream) {
if (ossClient == null) {
return false;
}
try {
ossClient.putObject(ossConfig.getBucketName(), storagePath, inputStream);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean deleteFile(String storagePath) {
if (ossClient == null) {
return false;
}
try {
ossClient.deleteObject(ossConfig.getBucketName(), storagePath);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean fileExists(String storagePath) {
if (ossClient == null) {
return false;
}
try {
return ossClient.doesObjectExist(ossConfig.getBucketName(), storagePath);
} catch (Exception e) {
return false;
}
}
}
@@ -0,0 +1,467 @@
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.sys.mapper.SysFileMapper;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchCreateOssFileDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
import top.xyquan.ecomdmbbackend.modules.sys.model.po.SysFilePO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.BatchSignUrlVO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileVO;
import top.xyquan.ecomdmbbackend.modules.sys.service.OssService;
import top.xyquan.ecomdmbbackend.modules.sys.service.SysFileService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import top.xyquan.ecomdmbbackend.utils.FileHashUtils;
import top.xyquan.ecomdmbbackend.utils.SysFileUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* 系统文件服务实现类
*/
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> implements SysFileService {
private final CurrentUserContext currentUserContext;
private final OssService ossService;
public SysFileServiceImpl(CurrentUserContext currentUserContext, OssService ossService) {
this.currentUserContext = currentUserContext;
this.ossService = ossService;
}
@Override
@Transactional
public List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files) {
if (files == null || files.isEmpty()) {
throw new BusinessException("文件列表不能为空");
}
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
List<SysFileUploadVO> result = new ArrayList<>();
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue;
}
// 计算文件哈希
String fileHash = FileHashUtils.calculateFileHash(file);
// 检查当前公司是否已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysFilePO::getCompanyId, companyId)
.eq(SysFilePO::getFileHash, fileHash)
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO existingFile = this.getOne(wrapper);
if (existingFile != null) {
// 当前公司已有相同文件,先验证文件是否真的存在可访问
if (verifyFileExists(existingFile)) {
result.add(convertToUploadVO(existingFile));
continue;
} else {
// 文件不存在,删除无效记录,继续处理
this.removeById(existingFile.getId());
}
}
// 检查是否有其他公司已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> otherCompanyWrapper = new LambdaQueryWrapper<>();
otherCompanyWrapper.eq(SysFilePO::getFileHash, fileHash)
.ne(SysFilePO::getCompanyId, companyId)
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO otherCompanyFile = this.getOne(otherCompanyWrapper);
String storagePath = null;
String storageType = "local"; // 上传接口始终使用本地存储
if (otherCompanyFile != null) {
// 其他公司已有相同文件,先验证文件是否真的存在可访问
if (verifyFileExists(otherCompanyFile)) {
// 文件存在,复制存储路径和类型
storagePath = otherCompanyFile.getStoragePath();
storageType = otherCompanyFile.getStorageType();
// 如果是本地存储,需要重新上传到当前公司的存储路径
if ("local".equals(storageType)) {
String relativePath = generateStoragePath(file.getOriginalFilename(), fileHash);
storagePath = "./" + relativePath;
saveFileToLocal(storagePath, file);
}
// 如果是OSS存储,直接使用相同的存储路径(OSS文件可以跨公司共享)
// 创建当前公司的文件记录
SysFilePO sysFile = new SysFilePO();
BeanUtils.copyProperties(otherCompanyFile, sysFile);
sysFile.setId(null);
sysFile.setCompanyId(companyId);
sysFile.setStoragePath(storagePath);
sysFile.setStorageType(storageType);
sysFile.setFilename(file.getOriginalFilename());
sysFile.setFileFormat(getFileExtension(file.getOriginalFilename()).toLowerCase());
sysFile.setMimeType(file.getContentType());
sysFile.setFileSize(file.getSize());
sysFile.setFileHash(fileHash);
sysFile.setUploadBy(userId);
sysFile.setUploadTime(LocalDateTime.now());
sysFile.setUpdateTime(null);
sysFile.setUpdateBy(null);
sysFile.setDeleteTime(null);
sysFile.setDeleteBy(null);
this.save(sysFile);
result.add(convertToUploadVO(sysFile));
} else {
// 文件不存在,删除无效记录,继续处理(当作新文件处理)
}
}
// 如果没有找到有效的其他公司文件,或者文件不存在,则作为新文件处理
if (storagePath == null) {
// 没有任何公司有相同文件,生成新的存储路径并上传(仅本地存储)
String relativePath = generateStoragePath(file.getOriginalFilename(), fileHash);
storagePath = "./" + relativePath;
saveFileToLocal(storagePath, file);
// 创建新记录
SysFilePO sysFile = new SysFilePO();
sysFile.setCompanyId(companyId);
sysFile.setStorageType(storageType);
sysFile.setStoragePath(storagePath);
sysFile.setFilename(file.getOriginalFilename());
sysFile.setFileFormat(getFileExtension(file.getOriginalFilename()).toLowerCase());
sysFile.setMimeType(file.getContentType());
sysFile.setFileSize(file.getSize());
sysFile.setFileHash(fileHash);
sysFile.setUploadBy(userId);
this.save(sysFile);
result.add(convertToUploadVO(sysFile));
}
}
return result;
}
@Override
public BatchSignUrlVO batchSignUrl(BatchSignUrlDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<BatchSignUrlVO.FileSignInfo> fileSignInfos = new ArrayList<>();
for (BatchSignUrlDTO.FileItem item : dto.getFiles()) {
BatchSignUrlVO.FileSignInfo signInfo = new BatchSignUrlVO.FileSignInfo();
signInfo.setFilename(item.getFilename());
signInfo.setFileHash(item.getFileHash());
// 检查当前公司是否已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysFilePO::getCompanyId, companyId)
.eq(SysFilePO::getFileHash, item.getFileHash())
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO existingFile = this.getOne(wrapper);
if (existingFile != null) {
// 文件已存在,先验证文件是否真的存在可访问
if (verifyFileExists(existingFile)) {
signInfo.setExists(true);
signInfo.setFileId(existingFile.getId());
signInfo.setFileInfo(convertToVO(existingFile));
// 生成访问URL(如果是OSS存储)
if ("oss".equals(existingFile.getStorageType())) {
signInfo.setAccessUrl(ossService.generateAccessUrl(existingFile.getStoragePath(), 60));
}
} else {
// 文件不存在,删除无效记录,继续处理
this.removeById(existingFile.getId());
existingFile = null;
}
}
if (existingFile == null) {
// 文件不存在,检查是否有其他公司存在OSS文件
LambdaQueryWrapper<SysFilePO> otherCompanyWrapper = new LambdaQueryWrapper<>();
otherCompanyWrapper.eq(SysFilePO::getFileHash, item.getFileHash())
.eq(SysFilePO::getStorageType, "oss")
.ne(SysFilePO::getCompanyId, companyId)
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO otherCompanyFile = this.getOne(otherCompanyWrapper);
if (otherCompanyFile != null) {
// 其他公司存在该OSS文件,先验证文件是否真的存在可访问
if (verifyFileExists(otherCompanyFile)) {
// 创建当前公司的文件记录
SysFilePO newFile = new SysFilePO();
BeanUtils.copyProperties(otherCompanyFile, newFile);
newFile.setId(null);
newFile.setCompanyId(companyId);
newFile.setFilename(item.getFilename());
newFile.setUploadBy(currentUserContext.getCurrentUserId());
newFile.setUploadTime(LocalDateTime.now());
newFile.setUpdateTime(null);
newFile.setUpdateBy(null);
newFile.setDeleteTime(null);
newFile.setDeleteBy(null);
this.save(newFile);
signInfo.setExists(true);
signInfo.setFileId(newFile.getId());
signInfo.setFileInfo(convertToVO(newFile));
// 生成访问URL
signInfo.setAccessUrl(ossService.generateAccessUrl(newFile.getStoragePath(), 60));
} else {
// 文件不存在,删除无效记录,继续处理
this.removeById(otherCompanyFile.getId());
otherCompanyFile = null;
}
}
if (otherCompanyFile == null) {
// 文件不存在,返回OSS签名URL(不创建记录)
signInfo.setExists(false);
String storagePath = generateStoragePath(item.getFilename(), item.getFileHash());
signInfo.setUploadUrl(ossService.generateUploadUrl(storagePath, 60));
}
}
fileSignInfos.add(signInfo);
}
BatchSignUrlVO result = new BatchSignUrlVO();
result.setFiles(fileSignInfos);
return result;
}
/**
* 生成存储路径(用于OSS签名URL生成)
*/
private String generateStoragePath(String originalFilename, String fileHash) {
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
String extension = getFileExtension(originalFilename);
String filename = fileHash + extension;
// OSS和本地存储都使用相同的路径格式,只是前缀不同
return "uploads/" + datePath + "/" + filename;
}
@Override
@Transactional
public List<SysFileVO> batchCreateOssFiles(BatchCreateOssFileDTO dto) {
if (dto.getFiles() == null || dto.getFiles().isEmpty()) {
throw new BusinessException("文件列表不能为空");
}
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
List<SysFileVO> result = new ArrayList<>();
for (BatchCreateOssFileDTO.FileItem item : dto.getFiles()) {
// 检查当前公司是否已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysFilePO::getCompanyId, companyId)
.eq(SysFilePO::getFileHash, item.getFileHash())
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO existingFile = this.getOne(wrapper);
if (existingFile != null) {
// 当前公司已有相同文件,直接返回
result.add(convertToVO(existingFile));
continue;
}
// 检查是否有其他公司已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> otherCompanyWrapper = new LambdaQueryWrapper<>();
otherCompanyWrapper.eq(SysFilePO::getFileHash, item.getFileHash())
.ne(SysFilePO::getCompanyId, companyId)
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO otherCompanyFile = this.getOne(otherCompanyWrapper);
SysFilePO sysFile;
if (otherCompanyFile != null) {
// 其他公司已有相同文件,复制记录并关联当前公司
sysFile = new SysFilePO();
BeanUtils.copyProperties(otherCompanyFile, sysFile);
sysFile.setId(null);
sysFile.setCompanyId(companyId);
sysFile.setStoragePath(item.getStoragePath());
sysFile.setStorageType("oss");
sysFile.setFilename(item.getFilename());
sysFile.setFileFormat(getFileExtension(item.getFilename()).toLowerCase());
sysFile.setMimeType(item.getMimeType());
sysFile.setFileSize(item.getFileSize());
sysFile.setFileHash(item.getFileHash());
sysFile.setCategory(item.getCategory());
sysFile.setTags(item.getTags());
sysFile.setRemark(item.getRemark());
sysFile.setUploadBy(userId);
sysFile.setUploadTime(LocalDateTime.now());
sysFile.setUpdateTime(null);
sysFile.setUpdateBy(null);
sysFile.setDeleteTime(null);
sysFile.setDeleteBy(null);
} else {
// 创建新记录
sysFile = new SysFilePO();
sysFile.setCompanyId(companyId);
sysFile.setStorageType("oss");
sysFile.setStoragePath(item.getStoragePath());
sysFile.setFilename(item.getFilename());
sysFile.setFileFormat(getFileExtension(item.getFilename()).toLowerCase());
sysFile.setMimeType(item.getMimeType());
sysFile.setFileSize(item.getFileSize());
sysFile.setFileHash(item.getFileHash());
sysFile.setCategory(item.getCategory());
sysFile.setTags(item.getTags());
sysFile.setRemark(item.getRemark());
sysFile.setUploadBy(userId);
}
this.save(sysFile);
result.add(convertToVO(sysFile));
}
return result;
}
/**
* 验证文件是否存在可访问
*
* @param sysFile 文件记录
* @return 文件是否存在
*/
private boolean verifyFileExists(SysFilePO sysFile) {
if (sysFile == null) {
return false;
}
try {
if ("oss".equals(sysFile.getStorageType())) {
// OSS存储:使用OSS SDK验证文件是否存在
return ossService != null && ossService.fileExists(sysFile.getStoragePath());
} else {
// 本地存储:检查文件系统
java.nio.file.Path path = java.nio.file.Paths.get(sysFile.getStoragePath());
return java.nio.file.Files.exists(path) && java.nio.file.Files.isRegularFile(path);
}
} catch (Exception e) {
return false;
}
}
/**
* 保存文件到本地存储
*/
private void saveFileToLocal(String storagePath, MultipartFile file) {
try {
java.nio.file.Path path = java.nio.file.Paths.get(storagePath);
java.nio.file.Files.createDirectories(path.getParent());
java.nio.file.Files.copy(file.getInputStream(), path);
} catch (Exception e) {
throw new BusinessException("文件保存到本地失败: " + e.getMessage());
}
}
/**
* 获取文件扩展名
*/
private String getFileExtension(String filename) {
if (filename == null || !filename.contains(".")) {
return "";
}
return filename.substring(filename.lastIndexOf("."));
}
/**
* 转换为上传响应VO(不包含敏感信息)
*/
private SysFileUploadVO convertToUploadVO(SysFilePO sysFile) {
SysFileUploadVO vo = new SysFileUploadVO();
vo.setId(sysFile.getId());
vo.setStorageType(sysFile.getStorageType());
vo.setStoragePath(sysFile.getStoragePath());
vo.setFilename(sysFile.getFilename());
vo.setFileFormat(sysFile.getFileFormat());
vo.setMimeType(sysFile.getMimeType());
vo.setFileSize(sysFile.getFileSize());
vo.setFileHash(sysFile.getFileHash());
vo.setCategory(sysFile.getCategory());
vo.setTags(sysFile.getTags());
vo.setRemark(sysFile.getRemark());
// 如果是OSS存储,生成访问URL
if ("oss".equals(sysFile.getStorageType())) {
vo.setAccessUrl(ossService.generateAccessUrl(sysFile.getStoragePath(), 60));
}
return vo;
}
@Override
public String getFileAccessUrl(Long fileId) {
if (fileId == null) {
throw new BusinessException("文件ID不能为空");
}
Long companyId = currentUserContext.getCurrentCompanyId();
// 查询文件记录
SysFilePO sysFile = this.getById(fileId);
if (sysFile == null) {
throw new BusinessException("文件不存在");
}
// 验证文件是否属于当前公司
if (!sysFile.getCompanyId().equals(companyId)) {
throw new BusinessException("无权访问该文件");
}
// 验证文件是否已删除
if (sysFile.getDeleteTime() != null) {
throw new BusinessException("文件已删除");
}
// 验证文件是否存在
if (!verifyFileExists(sysFile)) {
throw new BusinessException("文件不存在或无法访问");
}
// 使用工具类生成访问URL
String accessUrl = SysFileUtils.getFileAccessUrl(sysFile.getStoragePath(), sysFile.getStorageType());
if (accessUrl == null) {
throw new BusinessException("文件访问域名未配置");
}
return accessUrl;
}
/**
* 转换为VO
*/
private SysFileVO convertToVO(SysFilePO sysFile) {
SysFileVO vo = new SysFileVO();
BeanUtils.copyProperties(sysFile, vo);
// 如果是OSS存储,生成访问URL
if ("oss".equals(sysFile.getStorageType())) {
vo.setAccessUrl(ossService.generateAccessUrl(sysFile.getStoragePath(), 60));
}
return vo;
}
}