mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
wip: 重构文件系统中
This commit is contained in:
@@ -126,6 +126,12 @@
|
||||
<artifactId>commons-csv</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</dependency>
|
||||
<!-- 阿里云OSS -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>3.17.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+4
-4
@@ -23,7 +23,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopOverviewStatisticsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
|
||||
import top.xyquan.ecomdmbbackend.utils.FileUploadUtils;
|
||||
|
||||
/**
|
||||
@@ -80,14 +80,14 @@ public class ShopController {
|
||||
@Operation(summary = "上传店铺Logo", description = "上传店铺Logo图片,支持跨公司共享")
|
||||
@PostMapping("/upload-logo")
|
||||
@RequireRole(description = "上传店铺Logo", allowUser = false)
|
||||
public ApiResponse<MediaImageVO> uploadLogo(@RequestParam("file") MultipartFile file) {
|
||||
public ApiResponse<SysFileUploadVO> uploadLogo(@RequestParam("file") MultipartFile file) {
|
||||
// 检查是否为图片文件
|
||||
if (!FileUploadUtils.isImageFile(file.getOriginalFilename())) {
|
||||
return ApiResponse.fail("只能上传图片文件");
|
||||
}
|
||||
|
||||
MediaImageVO mediaImageVO = shopService.uploadLogo(file);
|
||||
return ApiResponse.success(mediaImageVO);
|
||||
SysFileUploadVO fileVO = shopService.uploadLogo(file);
|
||||
return ApiResponse.success(fileVO);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取店铺总览", description = "获取店铺总览,返回日期范围内每日的销售额、订单数、客单价、成本、退款金额、推广费、费比统计数据,包含时间范围的总值和每日数据数组")
|
||||
|
||||
-6
@@ -38,12 +38,6 @@ public class ProductPO {
|
||||
@TableField("product_code")
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 主图URL(冗余字段)
|
||||
*/
|
||||
@TableField("main_image")
|
||||
private String mainImage;
|
||||
|
||||
/**
|
||||
* 主图图片ID
|
||||
*/
|
||||
|
||||
-6
@@ -32,12 +32,6 @@ public class ShopPO {
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* logo URL(冗余字段)
|
||||
*/
|
||||
@TableField("logo")
|
||||
private String logo;
|
||||
|
||||
/**
|
||||
* logo图片ID
|
||||
*/
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
|
||||
|
||||
/**
|
||||
* 店铺服务接口
|
||||
@@ -58,7 +58,7 @@ public interface ShopService extends IService<ShopPO> {
|
||||
* @param file Logo文件
|
||||
* @return 上传后的图片信息
|
||||
*/
|
||||
MediaImageVO uploadLogo(MultipartFile file);
|
||||
SysFileUploadVO uploadLogo(MultipartFile file);
|
||||
|
||||
/**
|
||||
* 获取店铺总览(每日统计数据)
|
||||
|
||||
+33
-33
@@ -190,9 +190,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
@Transactional
|
||||
public void processImportTask(Long taskId) {
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新任务状态为处理中
|
||||
updateTaskStatus(taskId, "processing", null, 0, 0, 0);
|
||||
@@ -367,47 +367,47 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
throw new BusinessException("解析字段映射失败: fieldMapping必须是数组类型,当前类型: " + fieldMappingNode.getNodeType());
|
||||
}
|
||||
|
||||
List<MappingField> mappingFields = new java.util.ArrayList<>();
|
||||
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
|
||||
List<MappingField> mappingFields = new java.util.ArrayList<>();
|
||||
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
|
||||
if (!fieldNode.isObject()) {
|
||||
continue;
|
||||
}
|
||||
MappingField field = new MappingField();
|
||||
if (fieldNode.has("required")) {
|
||||
field.setRequired(fieldNode.get("required").asBoolean());
|
||||
MappingField field = new MappingField();
|
||||
if (fieldNode.has("required")) {
|
||||
field.setRequired(fieldNode.get("required").asBoolean());
|
||||
}
|
||||
if (fieldNode.has("fieldName")) {
|
||||
field.setFieldName(fieldNode.get("fieldName").asText());
|
||||
}
|
||||
if (fieldNode.has("fieldLabel")) {
|
||||
field.setFieldLabel(fieldNode.get("fieldLabel").asText());
|
||||
}
|
||||
if (fieldNode.has("fileFieldName")) {
|
||||
field.setFileFieldName(fieldNode.get("fileFieldName").asText());
|
||||
}
|
||||
mappingFields.add(field);
|
||||
}
|
||||
if (fieldNode.has("fieldName")) {
|
||||
field.setFieldName(fieldNode.get("fieldName").asText());
|
||||
}
|
||||
if (fieldNode.has("fieldLabel")) {
|
||||
field.setFieldLabel(fieldNode.get("fieldLabel").asText());
|
||||
}
|
||||
if (fieldNode.has("fileFieldName")) {
|
||||
field.setFileFieldName(fieldNode.get("fileFieldName").asText());
|
||||
}
|
||||
mappingFields.add(field);
|
||||
}
|
||||
config.setFieldMapping(mappingFields);
|
||||
config.setFieldMapping(mappingFields);
|
||||
|
||||
// 解析状态映射(可选)
|
||||
com.fasterxml.jackson.databind.JsonNode statusMappingNode = rootNode.get("statusMapping");
|
||||
if (statusMappingNode != null) {
|
||||
if (statusMappingNode.isArray()) {
|
||||
List<StatusMapping> statusMappings = new java.util.ArrayList<>();
|
||||
for (com.fasterxml.jackson.databind.JsonNode statusNode : statusMappingNode) {
|
||||
List<StatusMapping> statusMappings = new java.util.ArrayList<>();
|
||||
for (com.fasterxml.jackson.databind.JsonNode statusNode : statusMappingNode) {
|
||||
if (!statusNode.isObject()) {
|
||||
continue;
|
||||
}
|
||||
StatusMapping statusMapping = new StatusMapping();
|
||||
if (statusNode.has("csvStatus")) {
|
||||
statusMapping.setCsvStatus(statusNode.get("csvStatus").asText());
|
||||
}
|
||||
if (statusNode.has("mappedStatusId")) {
|
||||
statusMapping.setMappedStatusId(statusNode.get("mappedStatusId").asLong());
|
||||
}
|
||||
statusMappings.add(statusMapping);
|
||||
StatusMapping statusMapping = new StatusMapping();
|
||||
if (statusNode.has("csvStatus")) {
|
||||
statusMapping.setCsvStatus(statusNode.get("csvStatus").asText());
|
||||
}
|
||||
config.setStatusMapping(statusMappings);
|
||||
if (statusNode.has("mappedStatusId")) {
|
||||
statusMapping.setMappedStatusId(statusNode.get("mappedStatusId").asLong());
|
||||
}
|
||||
statusMappings.add(statusMapping);
|
||||
}
|
||||
config.setStatusMapping(statusMappings);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -756,8 +756,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
return null;
|
||||
}
|
||||
|
||||
String trimmedHeader = header.trim();
|
||||
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
|
||||
String trimmedHeader = header.trim();
|
||||
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
|
||||
|
||||
// 首先尝试精确匹配(考虑CSV解析器已经设置了setTrim(true))
|
||||
try {
|
||||
|
||||
+17
-15
@@ -21,9 +21,10 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
|
||||
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.mapper.SysFileMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.SysFilePO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
import top.xyquan.ecomdmbbackend.utils.SysFileUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -35,12 +36,12 @@ import java.util.stream.Collectors;
|
||||
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> implements ProductService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final MediaImageService mediaImageService;
|
||||
private final SysFileMapper sysFileMapper;
|
||||
private final ProductSpecService productSpecService;
|
||||
|
||||
public ProductServiceImpl(CurrentUserContext currentUserContext, MediaImageService mediaImageService, @Lazy ProductSpecService productSpecService) {
|
||||
public ProductServiceImpl(CurrentUserContext currentUserContext, SysFileMapper sysFileMapper, @Lazy ProductSpecService productSpecService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.mediaImageService = mediaImageService;
|
||||
this.sysFileMapper = sysFileMapper;
|
||||
this.productSpecService = productSpecService;
|
||||
}
|
||||
|
||||
@@ -81,11 +82,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
|
||||
// 处理主图图片关联
|
||||
if (createProductDTO.getMainImageId() != null) {
|
||||
MediaImageVO mainImage = mediaImageService.getImageById(createProductDTO.getMainImageId());
|
||||
if (mainImage != null) {
|
||||
product.setMainImageId(createProductDTO.getMainImageId());
|
||||
product.setMainImage(mainImage.getUrl()); // 设置冗余字段
|
||||
}
|
||||
product.setMainImageId(createProductDTO.getMainImageId());
|
||||
}
|
||||
|
||||
// 设置创建人ID
|
||||
@@ -162,11 +159,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
|
||||
// 处理主图图片关联
|
||||
if (updateProductDTO.getMainImageId() != null) {
|
||||
MediaImageVO mainImage = mediaImageService.getImageById(updateProductDTO.getMainImageId());
|
||||
if (mainImage != null) {
|
||||
product.setMainImageId(updateProductDTO.getMainImageId());
|
||||
product.setMainImage(mainImage.getUrl()); // 设置冗余字段
|
||||
}
|
||||
product.setMainImageId(updateProductDTO.getMainImageId());
|
||||
}
|
||||
|
||||
// 设置更新人ID
|
||||
@@ -335,6 +328,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
ProductVO productVO = new ProductVO();
|
||||
BeanUtils.copyProperties(product, productVO);
|
||||
|
||||
// 查询主图文件信息并生成访问URL
|
||||
if (product.getMainImageId() != null) {
|
||||
SysFilePO mainImageFile = sysFileMapper.selectById(product.getMainImageId());
|
||||
if (mainImageFile != null && mainImageFile.getDeleteTime() == null) {
|
||||
String mainImageUrl = SysFileUtils.getFileAccessUrl(mainImageFile.getStoragePath(), mainImageFile.getStorageType());
|
||||
productVO.setMainImage(mainImageUrl);
|
||||
}
|
||||
}
|
||||
|
||||
// 查询商品规格列表
|
||||
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
|
||||
specWrapper.eq(ProductSpecPO::getProductId, product.getId())
|
||||
|
||||
+30
-18
@@ -34,9 +34,12 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
|
||||
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.mapper.SysFileMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.SysFilePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.SysFileUploadVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.SysFileService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
import top.xyquan.ecomdmbbackend.utils.SysFileUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
@@ -44,6 +47,7 @@ import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -56,7 +60,8 @@ import java.util.stream.Collectors;
|
||||
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements ShopService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final MediaImageService mediaImageService;
|
||||
private final SysFileMapper sysFileMapper;
|
||||
private final SysFileService sysFileService;
|
||||
private final OrderMapper orderMapper;
|
||||
private final PromotionFeeMapper promotionFeeMapper;
|
||||
private final ProductMapper productMapper;
|
||||
@@ -64,13 +69,14 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
private final ProductSpecService productSpecService;
|
||||
private final OrderStatusService orderStatusService;
|
||||
|
||||
public ShopServiceImpl(CurrentUserContext currentUserContext, MediaImageService mediaImageService,
|
||||
public ShopServiceImpl(CurrentUserContext currentUserContext, SysFileMapper sysFileMapper, SysFileService sysFileService,
|
||||
OrderMapper orderMapper, PromotionFeeMapper promotionFeeMapper,
|
||||
ProductMapper productMapper,
|
||||
ShopProductRelationMapper shopProductRelationMapper, ProductSpecService productSpecService,
|
||||
OrderStatusService orderStatusService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.mediaImageService = mediaImageService;
|
||||
this.sysFileMapper = sysFileMapper;
|
||||
this.sysFileService = sysFileService;
|
||||
this.orderMapper = orderMapper;
|
||||
this.promotionFeeMapper = promotionFeeMapper;
|
||||
this.productMapper = productMapper;
|
||||
@@ -107,11 +113,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
|
||||
// 处理logo图片关联
|
||||
if (createShopDTO.getLogoImageId() != null) {
|
||||
MediaImageVO logoImage = mediaImageService.getImageById(createShopDTO.getLogoImageId());
|
||||
if (logoImage != null) {
|
||||
shop.setLogoImageId(createShopDTO.getLogoImageId());
|
||||
shop.setLogo(logoImage.getUrl()); // 设置冗余字段
|
||||
}
|
||||
shop.setLogoImageId(createShopDTO.getLogoImageId());
|
||||
}
|
||||
|
||||
// 设置创建人ID
|
||||
@@ -159,11 +161,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
|
||||
// 处理logo图片关联
|
||||
if (updateShopDTO.getLogoImageId() != null) {
|
||||
MediaImageVO logoImage = mediaImageService.getImageById(updateShopDTO.getLogoImageId());
|
||||
if (logoImage != null) {
|
||||
shop.setLogoImageId(updateShopDTO.getLogoImageId());
|
||||
shop.setLogo(logoImage.getUrl()); // 设置冗余字段
|
||||
}
|
||||
shop.setLogoImageId(updateShopDTO.getLogoImageId());
|
||||
}
|
||||
|
||||
// 设置更新人ID
|
||||
@@ -245,9 +243,13 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
* @return Logo图片VO
|
||||
*/
|
||||
@Override
|
||||
public MediaImageVO uploadLogo(MultipartFile file) {
|
||||
// 上传Logo到媒体模块(支持哈希校验和跨公司共享)
|
||||
return mediaImageService.uploadImageWithType(file, "logo");
|
||||
public SysFileUploadVO uploadLogo(MultipartFile file) {
|
||||
// 上传Logo到系统文件模块(支持哈希校验和跨公司共享)
|
||||
List<SysFileUploadVO> files = sysFileService.batchUploadFiles(Collections.singletonList(file));
|
||||
if (files.isEmpty()) {
|
||||
throw new BusinessException("Logo上传失败");
|
||||
}
|
||||
return files.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -269,6 +271,16 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
private ShopVO convertToVO(ShopPO shop) {
|
||||
ShopVO shopVO = new ShopVO();
|
||||
BeanUtils.copyProperties(shop, shopVO);
|
||||
|
||||
// 查询logo文件信息并生成访问URL
|
||||
if (shop.getLogoImageId() != null) {
|
||||
SysFilePO logoFile = sysFileMapper.selectById(shop.getLogoImageId());
|
||||
if (logoFile != null && logoFile.getDeleteTime() == null) {
|
||||
String logoUrl = SysFileUtils.getFileAccessUrl(logoFile.getStoragePath(), logoFile.getStorageType());
|
||||
shopVO.setLogo(logoUrl);
|
||||
}
|
||||
}
|
||||
|
||||
return shopVO;
|
||||
}
|
||||
|
||||
|
||||
+52
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+60
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+13
@@ -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> {
|
||||
}
|
||||
|
||||
+82
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+45
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+63
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+125
@@ -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;
|
||||
}
|
||||
|
||||
+46
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+49
@@ -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;
|
||||
}
|
||||
|
||||
+66
@@ -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;
|
||||
}
|
||||
|
||||
+53
@@ -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);
|
||||
}
|
||||
|
||||
+49
@@ -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);
|
||||
}
|
||||
|
||||
+101
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+467
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ CREATE TABLE `ec_shop` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '店铺ID',
|
||||
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '所属公司ID',
|
||||
`name` VARCHAR(200) NOT NULL COMMENT '店铺名称',
|
||||
`logo` varchar(255) DEFAULT NULL COMMENT 'logo URL(冗余字段)',
|
||||
`logo_image_id` BIGINT UNSIGNED DEFAULT NULL COMMENT 'logo图片ID',
|
||||
`platform` VARCHAR(50) DEFAULT NULL COMMENT '平台(如淘宝、京东、拼多多)',
|
||||
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
@@ -16,7 +15,7 @@ CREATE TABLE `ec_shop` (
|
||||
KEY `fk_ec_shop_creator` (`create_by`),
|
||||
KEY `fk_ec_shop_updater` (`update_by`),
|
||||
CONSTRAINT `fk_ec_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_shop_logo_image` FOREIGN KEY (`logo_image_id`) REFERENCES `media_image` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_shop_logo_image` FOREIGN KEY (`logo_image_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_shop_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_shop_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='电商-店铺表';
|
||||
@@ -27,7 +26,6 @@ CREATE TABLE `ec_product` (
|
||||
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`name` VARCHAR(255) NOT NULL COMMENT '商品名称',
|
||||
`product_code` VARCHAR(100) DEFAULT NULL COMMENT '商品编码',
|
||||
`main_image` VARCHAR(500) DEFAULT NULL COMMENT '主图URL(冗余字段)',
|
||||
`main_image_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '主图图片ID',
|
||||
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
@@ -40,7 +38,7 @@ CREATE TABLE `ec_product` (
|
||||
KEY `fk_ec_product_creator` (`create_by`),
|
||||
KEY `fk_ec_product_updater` (`update_by`),
|
||||
CONSTRAINT `fk_ec_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_main_image` FOREIGN KEY (`main_image_id`) REFERENCES `media_image` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_main_image` FOREIGN KEY (`main_image_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='电商-商品表(含成本价)';
|
||||
|
||||
@@ -98,4 +98,38 @@ CREATE TABLE `sys_menu_permission_map` (
|
||||
CONSTRAINT `fk_menu_permission_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_menu_permission_menu` FOREIGN KEY (`menu_id`) REFERENCES `sys_menu` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_menu_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `sys_permission` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='菜单与权限关联表';
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='菜单与权限关联表';
|
||||
|
||||
-- 统一文件资源表(替代 media_file 和 media_image)
|
||||
CREATE TABLE `sys_file` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '文件ID',
|
||||
`company_id` bigint unsigned NOT NULL COMMENT '公司ID',
|
||||
`storage_type` enum('local','oss','s3','qiniu','cos') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'local' COMMENT '存储类型(local-本地存储,oss-阿里云OSS,s3-AWS S3,qiniu-七牛云,cos-腾讯云COS)',
|
||||
`storage_path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '存储路径/Key(本地存储为相对路径,对象存储为存储Key)',
|
||||
`filename` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '原始文件名',
|
||||
`file_format` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '文件格式/扩展名,如 pdf/jpg/png/xlsx/doc/cad',
|
||||
`mime_type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT 'MIME类型,如 image/jpeg, application/pdf',
|
||||
`file_size` bigint unsigned DEFAULT NULL COMMENT '文件大小(字节)',
|
||||
`file_hash` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '文件哈希值(MD5/SHA256),用于去重',
|
||||
`category` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '文件分类(image-图片,avatar-头像,logo-Logo,document-文档,video-视频,audio-音频等)',
|
||||
`tags` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '标签,逗号分隔',
|
||||
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '文件描述/备注',
|
||||
`upload_by` bigint unsigned DEFAULT NULL COMMENT '上传人ID',
|
||||
`upload_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
`update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`update_by` bigint unsigned DEFAULT NULL COMMENT '更新人ID',
|
||||
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间(软删除)',
|
||||
`delete_by` bigint unsigned DEFAULT NULL COMMENT '删除人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
KEY `fk_sys_file_company` (`company_id`) USING BTREE,
|
||||
KEY `fk_sys_file_uploader` (`upload_by`) USING BTREE,
|
||||
KEY `idx_sys_file_hash` (`file_hash`) USING BTREE COMMENT '文件哈希索引,用于快速查找和去重',
|
||||
KEY `idx_sys_file_format` (`file_format`) USING BTREE COMMENT '文件格式索引',
|
||||
KEY `idx_sys_file_category` (`category`) USING BTREE COMMENT '文件分类索引',
|
||||
KEY `idx_sys_file_storage_type` (`storage_type`) USING BTREE COMMENT '存储类型索引',
|
||||
KEY `idx_sys_file_delete_time` (`delete_time`) USING BTREE COMMENT '删除时间索引,用于软删除查询',
|
||||
CONSTRAINT `fk_sys_file_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_sys_file_uploader` FOREIGN KEY (`upload_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_sys_file_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_sys_file_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='系统模块-统一文件资源表(支持本地存储和对象存储)';
|
||||
@@ -0,0 +1,71 @@
|
||||
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.config.OssConfig;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
/**
|
||||
* 系统文件工具类
|
||||
*/
|
||||
@Component
|
||||
public class SysFileUtils {
|
||||
|
||||
private static OssConfig staticOssConfig;
|
||||
private static String staticFileAccessDomain;
|
||||
|
||||
@Autowired
|
||||
private OssConfig ossConfig;
|
||||
|
||||
@Value("${file.access-domain:}")
|
||||
private String fileAccessDomain;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
staticOssConfig = ossConfig;
|
||||
staticFileAccessDomain = fileAccessDomain;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过存储路径和存储类型获取文件访问URL
|
||||
*
|
||||
* @param storagePath 存储路径/Key
|
||||
* @param storageType 存储类型(oss/local)
|
||||
* @return 文件访问URL
|
||||
*/
|
||||
public static String getFileAccessUrl(String storagePath, String storageType) {
|
||||
if (storagePath == null || storagePath.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ("oss".equals(storageType)) {
|
||||
// OSS存储:拼接OSS访问域名和存储路径
|
||||
if (staticOssConfig == null || staticOssConfig.getDomain() == null || staticOssConfig.getDomain().isEmpty()) {
|
||||
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 {
|
||||
// 本地存储:拼接文件访问域名和存储路径
|
||||
if (staticFileAccessDomain == null || staticFileAccessDomain.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
// 确保域名不以/结尾
|
||||
String domain = staticFileAccessDomain.endsWith("/")
|
||||
? staticFileAccessDomain.substring(0, staticFileAccessDomain.length() - 1)
|
||||
: staticFileAccessDomain;
|
||||
// 本地存储路径去掉 ./ 前缀
|
||||
String path = storagePath.startsWith("./")
|
||||
? storagePath.substring(2)
|
||||
: storagePath;
|
||||
path = path.startsWith("/") ? path : "/" + path;
|
||||
return domain + path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ springdoc:
|
||||
- "/menu/**"
|
||||
- "/permission/**"
|
||||
- "/user/**"
|
||||
- "/sys/file/**"
|
||||
packages-to-scan: "top.xyquan.ecomdmbbackend.modules.sys.controller"
|
||||
- group: "组织模块"
|
||||
paths-to-match:
|
||||
@@ -106,6 +107,19 @@ knife4j:
|
||||
# 开启footer自定义
|
||||
enable-footer-custom: false
|
||||
|
||||
# OSS配置
|
||||
oss:
|
||||
enabled: false
|
||||
endpoint: oss-cn-guangzhou.aliyuncs.com
|
||||
access-key-id: LTAI5t6QFVokh9o3Q3jvQjVc
|
||||
access-key-secret: 8FPEkc0aNETc3Oa7ErYZDTf8aIHpNb
|
||||
bucket-name: xyquan
|
||||
domain: https://xyquan.oss-cn-guangzhou.aliyuncs.com
|
||||
|
||||
# 文件访问配置
|
||||
file:
|
||||
access-domain: http://localhost:5666 # 本地文件访问域名
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
|
||||
Reference in New Issue
Block a user