refactor: 统一文件存储与上传流程,解耦 OSS 客户端、存储类型与前端上传模式

This commit is contained in:
2026-08-25 00:00:19 +08:00
parent 78dbc865fd
commit 81358e6d7c
57 changed files with 776 additions and 672 deletions
@@ -2,7 +2,6 @@ package top.xyquan.ecomdmbbackend.modules.ec.shop.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
@@ -15,8 +14,6 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.model.dto.UpdateShopDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
/**
* 店铺管理控制器
@@ -69,18 +66,6 @@ public class ShopController {
return ApiResponse.success("获取成功", vo);
}
@PostMapping("/upload-logo")
@RequirePermission(value = "ec:shop:create", description = "上传店铺Logo", allowSuper = true)
public ApiResponse<SysFileUploadVO> uploadLogo(@RequestParam("file") MultipartFile file) {
// 检查是否为图片文件
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
return ApiResponse.fail("只能上传图片文件");
}
SysFileUploadVO fileVO = shopService.uploadLogo(file);
return ApiResponse.success("Logo上传成功", fileVO);
}
@PostMapping("/products/list")
@RequirePermission(value = "ec:shop:read", description = "查询店铺商品列表", allowSuper = true)
public ApiResponse<PageResultVO<ProductVO>> getShopProductPage(
@@ -1,7 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.ec.shop.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.dto.CreateShopDTO;
@@ -11,7 +10,6 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.model.dto.UpdateShopDTO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
/**
* 店铺服务接口
@@ -58,14 +56,6 @@ public interface ShopService extends IService<ShopPO> {
*/
ShopVO getShopDetail(Long id);
/**
* 上传店铺Logo
*
* @param file Logo文件
* @return 上传后的图片信息
*/
SysFileUploadVO uploadLogo(MultipartFile file);
/**
* 分页获取店铺商品信息
*
@@ -31,12 +31,9 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import org.springframework.web.multipart.MultipartFile;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -223,21 +220,6 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
/**
* 上传Logo
* @param file 文件
* @return Logo图片VO
*/
@Override
public SysFileUploadVO uploadLogo(MultipartFile file) {
// 上传Logo到系统文件模块(支持哈希校验和跨公司共享),设置文件分类为logo
List<SysFileUploadVO> files = sysFileService.batchUploadFiles(Collections.singletonList(file), "logo");
if (files.isEmpty()) {
throw new BusinessException("Logo上传失败");
}
return files.get(0);
}
/**
* 转换为VO(单条;创建/更新等场景)
*/
@@ -2,7 +2,6 @@ package top.xyquan.ecomdmbbackend.modules.org.company.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
@@ -12,7 +11,6 @@ import top.xyquan.ecomdmbbackend.modules.org.company.model.dto.UpdateCompanyDTO;
import top.xyquan.ecomdmbbackend.modules.org.company.model.dto.CompanyFilterDTO;
import top.xyquan.ecomdmbbackend.modules.org.company.model.vo.CompanyVO;
import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
/**
* 公司管理控制器
@@ -57,16 +55,4 @@ public class CompanyController {
PageResultVO<CompanyVO> pageResult = companyService.getCompanyPage(pageQuery);
return ApiResponse.success("获取公司列表成功", pageResult);
}
@PostMapping("/upload-logo")
@RequirePermission(value = "org:company:update", description = "上传公司Logo", allowSuper = true)
public ApiResponse<CompanyVO> uploadLogo(@RequestParam("file") MultipartFile file) {
// 检查是否为图片文件
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
return ApiResponse.fail("只能上传图片文件");
}
CompanyVO companyVO = companyService.uploadLogo(file);
return ApiResponse.success("公司Logo上传成功", companyVO);
}
}
@@ -42,6 +42,8 @@ public class CreateCompanyDTO {
/**
* logo图片ID
*/
private Long logoImageId;
/**
* 状态 (0-禁用 1-正常)
*/
@@ -30,6 +30,8 @@ public class UpdateCompanyDTO {
/**
* logo图片ID
*/
private Long logoImageId;
/**
* 状态 (0-禁用 1-正常)
*/
@@ -57,7 +57,13 @@ public class CompanyPO {
private String email;
/**
* logo URL(冗余字段)
* logo 图片 ID(sys_file)
*/
@TableField("logo_image_id")
private Long logoImageId;
/**
* logo URL(冗余字段;有 logo_image_id 时查询可覆盖)
*/
@TableField("logo")
private String logo;
@@ -46,7 +46,12 @@ public class CompanyVO {
private String email;
/**
* logo
* logo 图片 ID
*/
private Long logoImageId;
/**
* logo 访问 URL
*/
private String logo;
@@ -1,7 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.org.company.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.org.company.model.dto.CreateCompanyDTO;
@@ -55,14 +54,6 @@ public interface CompanyService extends IService<CompanyPO> {
*/
PageResultVO<CompanyVO> getCompanyPage(PageQueryDTO<CompanyFilterDTO> pageQuery);
/**
* 上传公司Logo
*
* @param file Logo文件
* @return 更新后的公司信息
*/
CompanyVO uploadLogo(MultipartFile file);
/**
* 初始化公司菜单
*
@@ -18,7 +18,6 @@ import top.xyquan.ecomdmbbackend.modules.org.company.model.po.CompanyPO;
import top.xyquan.ecomdmbbackend.modules.org.company.model.vo.CompanyVO;
import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.org.company.menu.service.CompanyMenuService;
import top.xyquan.ecomdmbbackend.modules.org.department.service.DepartmentService;
import top.xyquan.ecomdmbbackend.modules.org.position.service.PositionService;
@@ -37,7 +36,6 @@ import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseInfo;
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseValidator;
import org.springframework.context.annotation.Lazy;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.crypto.password.PasswordEncoder;
@@ -119,6 +117,12 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
CompanyPO company = new CompanyPO();
BeanCopyUtils.copyProperties(createCompanyDTO, company);
// logo:有 fileId 时同步冗余 URL
if (createCompanyDTO.getLogoImageId() != null) {
company.setLogoImageId(createCompanyDTO.getLogoImageId());
company.setLogo(sysFileService.getFileAccessUrl(createCompanyDTO.getLogoImageId()));
}
// 设置默认值
if (company.getStatus() == null) {
company.setStatus(1);
@@ -209,6 +213,12 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// 更新公司
CompanyPO company = new CompanyPO();
BeanCopyUtils.copyProperties(updateCompanyDTO, company);
// logo:有 fileId 时同步冗余 URL
if (updateCompanyDTO.getLogoImageId() != null) {
company.setLogoImageId(updateCompanyDTO.getLogoImageId());
company.setLogo(sysFileService.getFileAccessUrl(updateCompanyDTO.getLogoImageId()));
}
// 设置公司ID(必须在updateById之前设置)
company.setId(id);
@@ -278,37 +288,6 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
return PageResultVO.create(records, pageResult.getTotal(), pageQuery.getPage(), pageQuery.getPageSize());
}
/**
* 上传公司Logo
* @param file 文件
* @return 公司VO
*/
@Override
public CompanyVO uploadLogo(MultipartFile file) {
// 获取当前用户所属公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("用户未关联公司");
}
// 查询公司信息
CompanyPO company = this.getById(companyId);
if (company == null) {
throw new BusinessException("公司不存在");
}
// 上传Logo到媒体模块(支持哈希校验和共享)
List<SysFileUploadVO> uploaded = sysFileService.batchUploadFiles(java.util.List.of(file), "logo", company.getId());
String logoUrl = uploaded.isEmpty() ? null : sysFileService.getFileAccessUrl(uploaded.get(0).getId());
// 更新公司Logo信息
company.setLogo(logoUrl);
this.updateById(company);
// 转换为VO并返回
return convertToVO(company);
}
/**
* 初始化公司菜单
* @param companyId 公司ID
@@ -437,6 +416,14 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
CompanyVO companyVO = new CompanyVO();
BeanCopyUtils.copyProperties(company, companyVO);
// 有系统文件 id 则覆盖 logo URL
if (company.getLogoImageId() != null) {
String accessUrl = sysFileService.getFileAccessUrl(company.getLogoImageId());
if (accessUrl != null && !accessUrl.isBlank()) {
companyVO.setLogo(accessUrl);
}
}
// 计算是否过期
if (company.getExpireTime() != null) {
companyVO.setExpired(company.getExpireTime().isBefore(LocalDateTime.now()));
@@ -0,0 +1,28 @@
package top.xyquan.ecomdmbbackend.modules.sys.config.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.sys.config.model.vo.SysConfigVO;
import top.xyquan.ecomdmbbackend.modules.sys.config.service.SysConfigService;
/**
* 系统配置接口(需登录)。
*/
@RestController
@RequestMapping("/api/sys/config")
public class SysConfigController {
private final SysConfigService sysConfigService;
public SysConfigController(SysConfigService sysConfigService) {
this.sysConfigService = sysConfigService;
}
/** 获取前端可用的系统配置(文件存储/上传模式等) */
@GetMapping
public ApiResponse<SysConfigVO> getConfig() {
return ApiResponse.success("获取系统配置成功", sysConfigService.getConfig());
}
}
@@ -0,0 +1,25 @@
package top.xyquan.ecomdmbbackend.modules.sys.config.model.vo;
import lombok.Builder;
import lombok.Data;
/**
* 系统配置(仅下发前端所需、不含敏感凭证)。
*/
@Data
@Builder
public class SysConfigVO {
private FileConfig file;
@Data
@Builder
public static class FileConfig {
/** 存储方式:local / oss */
private String storageType;
/** 上传方式:multipart(传后端)/ direct(直传对象存储) */
private String uploadMode;
/** 单文件大小上限(MB) */
private Integer maxFileSizeMb;
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.sys.config.service;
import top.xyquan.ecomdmbbackend.modules.sys.config.model.vo.SysConfigVO;
/**
* 系统配置查询(登录后下发前端)。
*/
public interface SysConfigService {
/** 获取可公开给前端的系统配置 */
SysConfigVO getConfig();
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.sys.config.service.impl;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.sys.config.model.vo.SysConfigVO;
import top.xyquan.ecomdmbbackend.modules.sys.config.service.SysConfigService;
import top.xyquan.ecomdmbbackend.modules.sys.file.support.FileStorageSupport;
/**
* 系统配置聚合:文件存储/上传模式等。
*/
@Service
public class SysConfigServiceImpl implements SysConfigService {
private final FileStorageSupport fileStorageSupport;
public SysConfigServiceImpl(FileStorageSupport fileStorageSupport) {
this.fileStorageSupport = fileStorageSupport;
}
@Override
public SysConfigVO getConfig() {
return SysConfigVO.builder()
.file(SysConfigVO.FileConfig.builder()
.storageType(fileStorageSupport.storageType())
.uploadMode(fileStorageSupport.uploadMode())
.maxFileSizeMb(fileStorageSupport.maxSizeMb())
.build())
.build();
}
}
@@ -10,11 +10,17 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 阿里云OSS配置
* 阿里云 OSS 客户端配置。
* <p>
* enabled 仅控制是否创建 SDK 客户端;文件落盘位置与前端上传方式见 sys.file。
*/
@Configuration
public class OssConfig {
/** 是否创建 OSS SDK 客户端(需配合有效凭证) */
@Value("${oss.enabled:false}")
private boolean enabled;
@Value("${oss.endpoint:}")
private String endpoint;
@@ -32,6 +38,9 @@ public class OssConfig {
@Bean
public OSS ossClient() {
if (!enabled) {
return null;
}
if (endpoint == null || endpoint.isEmpty() ||
accessKeyId == null || accessKeyId.isEmpty() ||
accessKeySecret == null || accessKeySecret.isEmpty()) {
@@ -62,6 +71,10 @@ public class OssConfig {
.build();
}
public boolean isEnabled() {
return enabled;
}
public String getEndpoint() {
return endpoint;
}
@@ -0,0 +1,28 @@
package top.xyquan.ecomdmbbackend.modules.sys.file.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 系统文件模块配置(sys.file)。
* <p>
* storage-type 决定物理存储位置;upload-mode 决定前端上传路径,二者独立配置。
*/
@Data
@Component
@ConfigurationProperties(prefix = "sys.file")
public class SysFileProperties {
/** 存储方式:local | oss */
private String storageType = "local";
/** 前端上传方式:multipart(经后端)| direct(直传对象存储) */
private String uploadMode = "multipart";
/** 本地文件访问域名(storage-type=local 时使用) */
private String accessDomain = "";
/** 单文件大小上限(MB) */
private int maxSizeMb = 50;
}
@@ -32,8 +32,12 @@ public class SysFileController {
}
@PostMapping("/batch-upload")
public ApiResponse<List<SysFileUploadVO>> batchUploadFiles(@RequestParam("files") List<MultipartFile> files) {
List<SysFileUploadVO> result = sysFileService.batchUploadFiles(files);
public ApiResponse<List<SysFileUploadVO>> batchUploadFiles(
@RequestParam("files") List<MultipartFile> files,
@RequestParam(value = "category", required = false) String category) {
List<SysFileUploadVO> result = category == null || category.isBlank()
? sysFileService.batchUploadFiles(files)
: sysFileService.batchUploadFiles(files, category);
return ApiResponse.success("文件批量上传成功", result);
}
@@ -9,6 +9,9 @@ import java.io.InputStream;
*/
public interface OssService {
/** OSS 是否可用(开关打开且客户端已创建) */
boolean isAvailable();
/**
* 生成上传Header签名(V1签名方式,HMAC-SHA1)
*
@@ -25,7 +25,12 @@ public class OssServiceImpl implements OssService {
public OssServiceImpl(OssConfig ossConfig) {
this.ossConfig = ossConfig;
this.ossClient = ossConfig.ossClient();
this.ossClient = ossConfig.isEnabled() ? ossConfig.ossClient() : null;
}
@Override
public boolean isAvailable() {
return ossConfig.isEnabled() && ossClient != null;
}
@Override
@@ -23,6 +23,7 @@ import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileVO;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.support.FileStorageSupport;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import top.xyquan.ecomdmbbackend.utils.FileHashUtils;
import top.xyquan.ecomdmbbackend.utils.SysFileUtils;
@@ -41,10 +42,14 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
private final CurrentUserContext currentUserContext;
private final OssService ossService;
private final FileStorageSupport fileStorageSupport;
public SysFileServiceImpl(CurrentUserContext currentUserContext, OssService ossService) {
public SysFileServiceImpl(CurrentUserContext currentUserContext,
OssService ossService,
FileStorageSupport fileStorageSupport) {
this.currentUserContext = currentUserContext;
this.ossService = ossService;
this.fileStorageSupport = fileStorageSupport;
}
@Override
@@ -57,16 +62,15 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
Long companyId = currentUserContext.getCurrentCompanyId() != null ? currentUserContext.getCurrentCompanyId().longValue() : null;
Long userId = currentUserContext.getCurrentUserId();
List<SysFileUploadVO> result = new ArrayList<>();
String storageType = fileStorageSupport.storageType();
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)
@@ -75,17 +79,13 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
SysFilePO existingFile = this.getOne(wrapper);
if (existingFile != null) {
// 当前公司已有相同文件,先验证文件是否真的存在可访问
if (verifyFileExists(existingFile)) {
result.add(convertToUploadVO(existingFile));
continue;
} else {
// 文件不存在,删除无效记录,继续处理
this.removeById(existingFile.getId());
}
this.removeById(existingFile.getId());
}
// 检查是否有其他公司已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> otherCompanyWrapper = new LambdaQueryWrapper<>();
otherCompanyWrapper.eq(SysFilePO::getFileHash, fileHash)
.isNull(SysFilePO::getDeleteTime)
@@ -93,30 +93,28 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
SysFilePO otherCompanyFile = this.getOne(otherCompanyWrapper);
String storagePath = null;
String storageType = "local"; // 上传接口始终使用本地存储
String resolvedStorageType = storageType;
if (otherCompanyFile != null) {
// 其他公司已有相同文件,先验证文件是否真的存在可访问
if (verifyFileExists(otherCompanyFile)) {
// 文件存在,复制存储路径和类型
storagePath = otherCompanyFile.getStoragePath();
storageType = otherCompanyFile.getStorageType();
// 如果是本地存储,需要重新上传到当前公司的存储路径
if ("local".equals(storageType)) {
resolvedStorageType = otherCompanyFile.getStorageType();
// 本地存储不可跨公司共享磁盘路径,需按当前模式重新落盘
if (FileStorageSupport.STORAGE_LOCAL.equals(resolvedStorageType)
|| (FileStorageSupport.STORAGE_LOCAL.equals(storageType)
&& !FileStorageSupport.STORAGE_OSS.equals(resolvedStorageType))) {
String relativePath = generateStoragePath(file.getOriginalFilename(), fileHash);
storagePath = "./" + relativePath;
saveFileToLocal(storagePath, file);
storagePath = fileStorageSupport.persist(relativePath, file);
resolvedStorageType = storageType;
}
// 如果是OSS存储,直接使用相同的存储路径(OSS文件可以跨公司共享)
// 创建当前公司的文件记录
SysFilePO sysFile = new SysFilePO();
BeanCopyUtils.copyProperties(otherCompanyFile, sysFile);
sysFile.setId(null);
sysFile.setCompanyId(companyId);
sysFile.setStoragePath(storagePath);
sysFile.setStorageType(storageType);
sysFile.setStorageType(resolvedStorageType);
sysFile.setFilename(file.getOriginalFilename());
sysFile.setFileFormat(getFileExtension(file.getOriginalFilename()).toLowerCase());
sysFile.setMimeType(file.getContentType());
@@ -128,22 +126,16 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
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);
// 创建新记录
storagePath = fileStorageSupport.persist(relativePath, file);
SysFilePO sysFile = new SysFilePO();
sysFile.setCompanyId(companyId);
sysFile.setStorageType(storageType);
@@ -152,8 +144,8 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
sysFile.setFileFormat(getFileExtension(file.getOriginalFilename()).toLowerCase());
sysFile.setMimeType(file.getContentType());
sysFile.setFileSize(file.getSize());
sysFile.setFileHash(fileHash);
sysFile.setUploadBy(userId);
sysFile.setFileHash(fileHash);
sysFile.setUploadBy(userId);
this.save(sysFile);
result.add(convertToUploadVO(sysFile));
@@ -178,10 +170,10 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
Long companyId = overrideCompanyId != null ? overrideCompanyId : (currentUserContext.getCurrentCompanyId() != null ? currentUserContext.getCurrentCompanyId().longValue() : null);
Long userId = currentUserContext.getCurrentUserId();
List<SysFileUploadVO> result = new ArrayList<>();
String storageType = fileStorageSupport.storageType();
for (MultipartFile file : files) {
if (file.isEmpty()) { continue; }
String fileHash = FileHashUtils.calculateFileHash(file);
// 查询当前公司是否已有相同哈希的文件
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
if (companyId != null) {
wrapper.eq(SysFilePO::getCompanyId, companyId);
@@ -196,9 +188,8 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
result.add(convertToUploadVO(existingFile));
continue;
}
String storageType = "local";
String storagePath = "./" + generateStoragePath(file.getOriginalFilename(), fileHash);
saveFileToLocal(storagePath, file);
String relativePath = generateStoragePath(file.getOriginalFilename(), fileHash);
String storagePath = fileStorageSupport.persist(relativePath, file);
SysFilePO sysFile = new SysFilePO();
sysFile.setCompanyId(companyId);
sysFile.setStorageType(storageType);
@@ -220,6 +211,10 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
@Override
public BatchSignUrlVO batchSignUrl(BatchSignUrlDTO dto) {
if (!fileStorageSupport.isDirectUpload()) {
throw new BusinessException("当前 upload-mode 非 direct,请使用 multipart 上传接口");
}
fileStorageSupport.ensureOssAvailable();
Long companyId = currentUserContext.getCurrentCompanyId() != null ? currentUserContext.getCurrentCompanyId().longValue() : null;
List<BatchSignUrlVO.FileSignInfo> fileSignInfos = new ArrayList<>();
@@ -328,6 +323,10 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
@Override
@Transactional
public List<SysFileVO> batchCreateOssFiles(BatchCreateOssFileDTO dto) {
if (!fileStorageSupport.isOssStorage()) {
throw new BusinessException("当前 storage-type 非 oss,请使用 multipart 上传接口");
}
fileStorageSupport.ensureOssAvailable();
if (dto.getFiles() == null || dto.getFiles().isEmpty()) {
throw new BusinessException("文件列表不能为空");
}
@@ -431,19 +430,6 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
}
}
/**
* 保存文件到本地存储
*/
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());
}
}
/**
* 获取文件扩展名
*/
@@ -470,11 +456,7 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
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));
}
vo.setAccessUrl(SysFileUtils.getFileAccessUrl(sysFile.getStoragePath(), sysFile.getStorageType()));
return vo;
}
@@ -0,0 +1,128 @@
package top.xyquan.ecomdmbbackend.modules.sys.file.support;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.sys.file.config.SysFileProperties;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
/**
* 文件存储/上传模式:读取 sys.file 配置,与 oss.enabled(仅控制 SDK 客户端)解耦。
*/
@Component
public class FileStorageSupport {
public static final String STORAGE_LOCAL = "local";
public static final String STORAGE_OSS = "oss";
/** 前端 multipart 传到后端 */
public static final String UPLOAD_MULTIPART = "multipart";
/** 前端直传对象存储 */
public static final String UPLOAD_DIRECT = "direct";
private final SysFileProperties sysFileProperties;
private final OssService ossService;
public FileStorageSupport(SysFileProperties sysFileProperties, OssService ossService) {
this.sysFileProperties = sysFileProperties;
this.ossService = ossService;
}
@PostConstruct
void validateConfig() {
if (isDirectUpload() && !isOssStorage()) {
throw new IllegalStateException(
"sys.file.upload-mode=direct 时 storage-type 必须为 oss");
}
if (isOssStorage() && !ossService.isAvailable()) {
throw new IllegalStateException(
"sys.file.storage-type=oss 但 OSS 客户端不可用,请配置 oss.enabled 与凭证");
}
if (isDirectUpload() && !ossService.isAvailable()) {
throw new IllegalStateException(
"sys.file.upload-mode=direct 但 OSS 客户端不可用,请配置 oss.enabled 与凭证");
}
}
/** 落库 storage_type */
public String storageType() {
return normalizeStorageType(sysFileProperties.getStorageType());
}
/** 下发给前端的上传方式 */
public String uploadMode() {
return normalizeUploadMode(sysFileProperties.getUploadMode());
}
public boolean isOssStorage() {
return STORAGE_OSS.equals(storageType());
}
public boolean isDirectUpload() {
return UPLOAD_DIRECT.equals(uploadMode());
}
public int maxSizeMb() {
return sysFileProperties.getMaxSizeMb();
}
/**
* 写入物理存储并返回应写入 sys_file.storage_path 的值。
*
* @param relativePath 统一相对路径,如 uploads/2026/03/xxx.png
*/
public String persist(String relativePath, MultipartFile file) {
if (isOssStorage()) {
ensureOssAvailable();
try {
boolean ok = ossService.uploadFile(relativePath, file.getInputStream());
if (!ok) {
throw new BusinessException("文件上传到对象存储失败");
}
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("文件上传到对象存储失败: " + e.getMessage());
}
return relativePath;
}
String localPath = "./" + relativePath;
try {
java.nio.file.Path path = java.nio.file.Paths.get(localPath);
java.nio.file.Files.createDirectories(path.getParent());
java.nio.file.Files.copy(file.getInputStream(), path);
} catch (Exception e) {
throw new BusinessException("文件保存到本地失败: " + e.getMessage());
}
return localPath;
}
public void ensureOssAvailable() {
if (!ossService.isAvailable()) {
throw new BusinessException("对象存储未配置或不可用");
}
}
private static String normalizeStorageType(String raw) {
if (!StringUtils.hasText(raw)) {
return STORAGE_LOCAL;
}
String v = raw.trim().toLowerCase();
if (STORAGE_OSS.equals(v)) {
return STORAGE_OSS;
}
return STORAGE_LOCAL;
}
private static String normalizeUploadMode(String raw) {
if (!StringUtils.hasText(raw)) {
return UPLOAD_MULTIPART;
}
String v = raw.trim().toLowerCase();
if (UPLOAD_DIRECT.equals(v)) {
return UPLOAD_DIRECT;
}
return UPLOAD_MULTIPART;
}
}
@@ -2,7 +2,6 @@ package top.xyquan.ecomdmbbackend.modules.sys.user.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
@@ -15,7 +14,6 @@ import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserCompanySummaryVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserVO;
import top.xyquan.ecomdmbbackend.modules.sys.menu.service.UserMenuService;
import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
import java.util.List;
@@ -59,18 +57,6 @@ public class UserController {
return ApiResponse.success("密码修改成功");
}
@PostMapping("/upload-avatar")
@RequirePermission(value = "sys:user:update", description = "上传用户头像", allowSuper = true)
public ApiResponse<UserVO> uploadAvatar(@RequestParam("file") MultipartFile file) {
// 检查是否为图片文件
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
return ApiResponse.fail("只能上传图片文件");
}
UserVO userVO = userService.uploadAvatar(file);
return ApiResponse.success("头像上传成功", userVO);
}
@GetMapping("/menu")
public ApiResponse<List<UserMenuVO>> getUserMenus() {
List<UserMenuVO> userMenuVOS = userMenuService.getUserMenus();
@@ -1,7 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.sys.user.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.sys.auth.model.dto.ChangePasswordDTO;
@@ -68,14 +67,6 @@ public interface UserService extends IService<UserPO> {
*/
void changePassword(ChangePasswordDTO changePasswordDTO);
/**
* 上传用户头像
*
* @param file 头像文件
* @return 更新后的用户信息
*/
UserVO uploadAvatar(MultipartFile file);
/**
* 刷新访问令牌
*
@@ -26,12 +26,10 @@ import top.xyquan.ecomdmbbackend.modules.sys.user.model.vo.UserVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileUploadVO;
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
import top.xyquan.ecomdmbbackend.utils.SecurityUtils;
import top.xyquan.ecomdmbbackend.utils.AccessTokenPayload;
import top.xyquan.ecomdmbbackend.utils.RefreshTokenPayload;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;
@@ -292,40 +290,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements
this.updateById(user);
}
/**
* 上传头像
* @param file 文件
* @return 用户VO
*/
@Override
public UserVO uploadAvatar(MultipartFile file) {
// 从Security上下文获取用户ID
Long userId = SecurityUtils.getCurrentUserId();
if (userId == null) {
throw new BusinessException("用户未登录");
}
// 查询用户信息
UserPO user = this.getById(userId);
if (user == null) {
throw new BusinessException("用户不存在");
}
// 上传头像到媒体模块(支持哈希校验和共享)
List<SysFileUploadVO> uploaded = sysFileService.batchUploadFiles(java.util.List.of(file), "avatar");
String avatarUrl = uploaded.isEmpty() ? null : sysFileService.getFileAccessUrl(uploaded.get(0).getId());
// 更新用户头像信息
user.setAvatar(avatarUrl);
this.updateById(user);
// 转换为VO并返回
UserVO userVO = new UserVO();
BeanCopyUtils.copyProperties(user, userVO);
fillCompanyFromCurrentToken(userVO);
return userVO;
}
/**
* 刷新令牌
* @param refreshTokenDTO 刷新令牌DTO
@@ -1,9 +1,9 @@
package top.xyquan.ecomdmbbackend.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.sys.file.config.OssConfig;
import top.xyquan.ecomdmbbackend.modules.sys.file.config.SysFileProperties;
import jakarta.annotation.PostConstruct;
@@ -19,13 +19,13 @@ public class SysFileUtils {
@Autowired
private OssConfig ossConfig;
@Value("${file.access-domain:}")
private String fileAccessDomain;
@Autowired
private SysFileProperties sysFileProperties;
@PostConstruct
public void init() {
staticOssConfig = ossConfig;
staticFileAccessDomain = fileAccessDomain;
staticFileAccessDomain = sysFileProperties.getAccessDomain();
}
/**
@@ -46,26 +46,22 @@ public class SysFileUtils {
return null;
}
String domain = staticOssConfig.getDomain();
// 确保域名不以/结尾,路径不以/开头
domain = domain.endsWith("/") ? domain.substring(0, domain.length() - 1) : domain;
String path = storagePath.startsWith("/") ? storagePath : "/" + storagePath;
return domain + path;
} else {
// 本地存储:拼接文件访问域名和存储路径
// 本地存储:拼接 sys.file.access-domain 与路径
if (staticFileAccessDomain == null || staticFileAccessDomain.isEmpty()) {
return null;
}
// 确保域名不以/结尾
String domain = staticFileAccessDomain.endsWith("/")
? staticFileAccessDomain.substring(0, staticFileAccessDomain.length() - 1)
String domain = staticFileAccessDomain.endsWith("/")
? staticFileAccessDomain.substring(0, staticFileAccessDomain.length() - 1)
: staticFileAccessDomain;
// 本地存储路径去掉 ./ 前缀
String path = storagePath.startsWith("./")
? storagePath.substring(2)
String path = storagePath.startsWith("./")
? storagePath.substring(2)
: storagePath;
path = path.startsWith("/") ? path : "/" + path;
return domain + path;
}
}
}