mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
refactor: 统一文件存储与上传流程,解耦 OSS 客户端、存储类型与前端上传模式
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
HELP.md
|
||||
target/
|
||||
temp/
|
||||
uploads/
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
@@ -15,7 +15,8 @@ CREATE TABLE `org_company` (
|
||||
`owner_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '公司拥有者姓名',
|
||||
`owner_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '公司拥有者电话',
|
||||
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
|
||||
`logo` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'logo URL(冗余字段)',
|
||||
`logo_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'logo图片ID',
|
||||
`logo` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'logo URL(冗余字段;有 logo_image_id 时查询覆盖)',
|
||||
`status` int NOT NULL DEFAULT 1 COMMENT '状态 (0-禁用 1-正常)',
|
||||
`expire_time` timestamp NULL DEFAULT NULL COMMENT '订阅到期时间',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
@@ -25,8 +26,10 @@ CREATE TABLE `org_company` (
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
INDEX `fk_org_company_creator`(`create_by` ASC) USING BTREE,
|
||||
INDEX `fk_org_company_updater`(`update_by` ASC) USING BTREE,
|
||||
INDEX `fk_org_company_logo_image`(`logo_image_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_org_company_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_org_company_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
CONSTRAINT `fk_org_company_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_org_company_logo_image` FOREIGN KEY (`logo_image_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '系统模块-公司表'
|
||||
|
||||
-- ========================================
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 公司 Logo 对齐店铺:增加 logo_image_id,保留 logo 为访问 URL 冗余
|
||||
ALTER TABLE `org_company`
|
||||
ADD COLUMN `logo_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'logo图片ID' AFTER `email`,
|
||||
ADD INDEX `fk_org_company_logo_image` (`logo_image_id` ASC),
|
||||
ADD CONSTRAINT `fk_org_company_logo_image` FOREIGN KEY (`logo_image_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
-15
@@ -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(
|
||||
|
||||
-10
@@ -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);
|
||||
|
||||
/**
|
||||
* 分页获取店铺商品信息
|
||||
*
|
||||
|
||||
-18
@@ -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(单条;创建/更新等场景)
|
||||
*/
|
||||
|
||||
-14
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -42,6 +42,8 @@ public class CreateCompanyDTO {
|
||||
/**
|
||||
* logo图片ID
|
||||
*/
|
||||
private Long logoImageId;
|
||||
|
||||
/**
|
||||
* 状态 (0-禁用 1-正常)
|
||||
*/
|
||||
|
||||
+2
@@ -30,6 +30,8 @@ public class UpdateCompanyDTO {
|
||||
/**
|
||||
* logo图片ID
|
||||
*/
|
||||
private Long logoImageId;
|
||||
|
||||
/**
|
||||
* 状态 (0-禁用 1-正常)
|
||||
*/
|
||||
|
||||
+7
-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;
|
||||
|
||||
+6
-1
@@ -46,7 +46,12 @@ public class CompanyVO {
|
||||
private String email;
|
||||
|
||||
/**
|
||||
* logo
|
||||
* logo 图片 ID
|
||||
*/
|
||||
private Long logoImageId;
|
||||
|
||||
/**
|
||||
* logo 访问 URL
|
||||
*/
|
||||
private String logo;
|
||||
|
||||
|
||||
-9
@@ -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);
|
||||
|
||||
/**
|
||||
* 初始化公司菜单
|
||||
*
|
||||
|
||||
+20
-33
@@ -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()));
|
||||
|
||||
+28
@@ -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());
|
||||
}
|
||||
}
|
||||
+25
@@ -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;
|
||||
}
|
||||
}
|
||||
+12
@@ -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();
|
||||
}
|
||||
+30
@@ -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();
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -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;
|
||||
}
|
||||
|
||||
+28
@@ -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;
|
||||
}
|
||||
+6
-2
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -9,6 +9,9 @@ import java.io.InputStream;
|
||||
*/
|
||||
public interface OssService {
|
||||
|
||||
/** OSS 是否可用(开关打开且客户端已创建) */
|
||||
boolean isAvailable();
|
||||
|
||||
/**
|
||||
* 生成上传Header签名(V1签名方式,HMAC-SHA1)
|
||||
*
|
||||
|
||||
+6
-1
@@ -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
|
||||
|
||||
+38
-56
@@ -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;
|
||||
}
|
||||
|
||||
+128
@@ -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;
|
||||
}
|
||||
}
|
||||
-14
@@ -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();
|
||||
|
||||
-9
@@ -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);
|
||||
|
||||
/**
|
||||
* 刷新访问令牌
|
||||
*
|
||||
|
||||
-36
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,13 +31,18 @@ mybatis-plus:
|
||||
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
|
||||
oss:
|
||||
enabled: false
|
||||
enabled: true
|
||||
access-key-id: LTAI5t8oyyor6wLrQasDUQA3
|
||||
access-key-secret: U0d3BeKADTJUteSsT5gBtxzlbHoJFi
|
||||
domain: https://xyquan.oss-cn-guangzhou.aliyuncs.com
|
||||
|
||||
file:
|
||||
access-domain: http://localhost:5666
|
||||
sys:
|
||||
file:
|
||||
# local 本地存储;oss 阿里云 OSS
|
||||
# multipart 通过后端上传;direct 直接上传
|
||||
storage-type: oss
|
||||
upload-mode: direct
|
||||
access-domain: http://localhost:5666
|
||||
|
||||
ecom:
|
||||
license:
|
||||
|
||||
@@ -32,8 +32,11 @@ oss:
|
||||
access-key-secret: U0d3BeKADTJUteSsT5gBtxzlbHoJFi
|
||||
domain: https://xyquan.oss-cn-guangzhou.aliyuncs.com
|
||||
|
||||
file:
|
||||
access-domain: https://staging.example.com
|
||||
sys:
|
||||
file:
|
||||
storage-type: oss
|
||||
upload-mode: direct
|
||||
access-domain: https://staging.example.com
|
||||
|
||||
ecom:
|
||||
license:
|
||||
|
||||
@@ -33,8 +33,11 @@ oss:
|
||||
access-key-secret: U0d3BeKADTJUteSsT5gBtxzlbHoJFi
|
||||
domain: https://xyquan.oss-cn-guangzhou.aliyuncs.com
|
||||
|
||||
file:
|
||||
access-domain: https://api.example.com
|
||||
sys:
|
||||
file:
|
||||
storage-type: oss
|
||||
upload-mode: direct
|
||||
access-domain: https://api.example.com
|
||||
|
||||
ecom:
|
||||
license:
|
||||
|
||||
@@ -31,8 +31,11 @@ oss:
|
||||
access-key-secret: U0d3BeKADTJUteSsT5gBtxzlbHoJFi
|
||||
domain: https://xyquan.oss-cn-guangzhou.aliyuncs.com
|
||||
|
||||
file:
|
||||
access-domain: http://localhost:5666
|
||||
sys:
|
||||
file:
|
||||
storage-type: oss
|
||||
upload-mode: direct
|
||||
access-domain: http://localhost:5666
|
||||
|
||||
ecom:
|
||||
license:
|
||||
|
||||
@@ -124,9 +124,15 @@ mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
|
||||
# OSS(开关与凭证见各环境配置)
|
||||
# OSS 客户端(凭证与开关;是否用于存文件由 sys.file.storage-type 决定)
|
||||
oss:
|
||||
endpoint: https://oss-cn-guangzhou.aliyuncs.com
|
||||
bucket-name: xyquan
|
||||
enabled: false
|
||||
|
||||
# 拼多多渠道配置见 config/channel-pdd.yml
|
||||
# 系统文件:storage-type 决定落盘位置,upload-mode 决定前端上传路径
|
||||
sys:
|
||||
file:
|
||||
storage-type: local
|
||||
upload-mode: multipart
|
||||
max-size-mb: 50
|
||||
|
||||
@@ -34,16 +34,3 @@ export async function updateCompanyApi(id: number, data: CompanyDTO.UpdateCompan
|
||||
export async function deleteCompanyApi(id: number) {
|
||||
return requestClient.delete<void>(`/company/delete/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传公司Logo
|
||||
*/
|
||||
export async function uploadCompanyLogoApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<CompanyVO.CompanyInfoVO>('/company/upload-logo', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ export namespace CompanyVO {
|
||||
email?: string;
|
||||
/** logo */
|
||||
logo?: string;
|
||||
/** logo 图片 ID */
|
||||
logoImageId?: number;
|
||||
/** 状态 (0-禁用 1-正常) */
|
||||
status: number;
|
||||
/** 订阅到期时间 */
|
||||
|
||||
@@ -44,19 +44,6 @@ export async function getShopDetailApi(id: number) {
|
||||
return requestClient.get<ShopVO.Info>(`/ec/shop/detail/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传店铺Logo
|
||||
*/
|
||||
export async function uploadShopLogoApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<ShopVO.Info>('/ec/shop/upload-logo', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取店铺商品信息
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* 系统配置 API(需登录)
|
||||
*/
|
||||
import type { SysConfigVO } from './types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/** 获取系统配置(文件存储/上传模式等) */
|
||||
export async function getSysConfigApi() {
|
||||
return requestClient.get<SysConfigVO.Config>('/sys/config');
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 系统配置 VO
|
||||
*/
|
||||
export namespace SysConfigVO {
|
||||
export interface Config {
|
||||
file: FileConfig;
|
||||
}
|
||||
|
||||
export interface FileConfig {
|
||||
/** 存储方式:local / oss */
|
||||
storageType: 'local' | 'oss' | string;
|
||||
/** 上传方式:multipart(传后端)/ direct(直传对象存储) */
|
||||
uploadMode: 'multipart' | 'direct' | string;
|
||||
/** 单文件大小上限(MB) */
|
||||
maxFileSizeMb: number;
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,18 @@ import { requestClient } from '#/api/request';
|
||||
*/
|
||||
|
||||
/**
|
||||
* 批量上传文件
|
||||
* 批量上传文件(multipart,由后端按 storageType 落盘)
|
||||
* @param files 文件列表
|
||||
* @param category 可选分类
|
||||
*/
|
||||
export async function batchUploadFilesApi(files: File[]) {
|
||||
export async function batchUploadFilesApi(files: File[], category?: string) {
|
||||
const formData = new FormData();
|
||||
files.forEach((file) => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
if (category) {
|
||||
formData.append('category', category);
|
||||
}
|
||||
return requestClient.post<FileVO.Upload[]>(
|
||||
'/sys/file/batch-upload',
|
||||
formData,
|
||||
|
||||
@@ -35,19 +35,6 @@ export async function changePasswordApi(data: UserDTO.ChangePasswordDTO) {
|
||||
return requestClient.post<void>('/user/change-password', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传用户头像
|
||||
*/
|
||||
export async function uploadAvatarApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<UserVO.UserInfoVO>('/user/upload-avatar', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户菜单
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImportTaskVO } from '#/api/ec/import/task';
|
||||
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
@@ -89,9 +89,6 @@ function formatTime(time: string): string {
|
||||
return new Date(time).toLocaleString();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
importTaskStore.init();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -65,8 +65,11 @@ const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
// 登录布局挂载:先建用户级 SSE,再拉导入任务
|
||||
// 登录布局挂载:已登录才建 SSE 与导入任务(welcome 等 ignoreAccess 页未登录也会进此布局)
|
||||
onMounted(() => {
|
||||
if (!accessStore.accessToken) {
|
||||
return;
|
||||
}
|
||||
realtimeStore.start();
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
@@ -95,6 +95,14 @@ function setupAccessGuard(router: Router) {
|
||||
const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());
|
||||
const userRoles = userInfo.roles ?? [];
|
||||
|
||||
// 系统配置(刷新页面后补拉)
|
||||
try {
|
||||
const { useAppConfigStore } = await import('#/store/app-config');
|
||||
await useAppConfigStore().ensureLoaded();
|
||||
} catch (error) {
|
||||
console.warn('获取系统配置失败:', error);
|
||||
}
|
||||
|
||||
// 生成菜单和路由
|
||||
const { accessibleMenus, accessibleRoutes } = await generateAccess({
|
||||
roles: userRoles,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { SysConfigVO } from '#/api/sys/config';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { getSysConfigApi } from '#/api/sys/config';
|
||||
|
||||
/**
|
||||
* 系统配置(登录后拉取;含文件上传模式等)。
|
||||
*/
|
||||
export const useAppConfigStore = defineStore('app-config', () => {
|
||||
const config = ref<null | SysConfigVO.Config>(null);
|
||||
const loaded = ref(false);
|
||||
const loading = ref(false);
|
||||
|
||||
const file = computed(() => config.value?.file ?? null);
|
||||
const uploadMode = computed(() => file.value?.uploadMode ?? 'multipart');
|
||||
const storageType = computed(() => file.value?.storageType ?? 'local');
|
||||
const maxFileSizeMb = computed(() => file.value?.maxFileSizeMb ?? 50);
|
||||
const isDirectUpload = computed(() => uploadMode.value === 'direct');
|
||||
|
||||
async function fetchConfig(force = false) {
|
||||
if (loaded.value && !force) {
|
||||
return config.value;
|
||||
}
|
||||
if (loading.value) {
|
||||
return config.value;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
config.value = await getSysConfigApi();
|
||||
loaded.value = true;
|
||||
return config.value;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 确保已加载;未加载则请求 */
|
||||
async function ensureLoaded() {
|
||||
if (!loaded.value) {
|
||||
await fetchConfig();
|
||||
}
|
||||
return config.value;
|
||||
}
|
||||
|
||||
function $reset() {
|
||||
config.value = null;
|
||||
loaded.value = false;
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
return {
|
||||
config,
|
||||
loaded,
|
||||
loading,
|
||||
file,
|
||||
uploadMode,
|
||||
storageType,
|
||||
maxFileSizeMb,
|
||||
isDirectUpload,
|
||||
fetchConfig,
|
||||
ensureLoaded,
|
||||
$reset,
|
||||
};
|
||||
});
|
||||
@@ -19,10 +19,12 @@ import {
|
||||
registerApi,
|
||||
} from '#/api';
|
||||
import { $t } from '#/locales';
|
||||
import { useAppConfigStore } from '#/store/app-config';
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const accessStore = useAccessStore();
|
||||
const userStore = useUserStore();
|
||||
const appConfigStore = useAppConfigStore();
|
||||
const router = useRouter();
|
||||
|
||||
const loginLoading = ref(false);
|
||||
@@ -64,6 +66,13 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// 获取用户信息
|
||||
userInfo = await fetchUserInfo();
|
||||
|
||||
// 系统配置(上传模式等)
|
||||
try {
|
||||
await appConfigStore.fetchConfig(true);
|
||||
} catch (error) {
|
||||
console.warn('获取系统配置失败:', error);
|
||||
}
|
||||
|
||||
// 获取用户权限码(可选,如果接口不存在则跳过)
|
||||
try {
|
||||
const accessCodes = await getAccessCodesApi();
|
||||
@@ -138,6 +147,13 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// 获取用户信息
|
||||
userInfo = await fetchUserInfo();
|
||||
|
||||
// 系统配置(上传模式等)
|
||||
try {
|
||||
await appConfigStore.fetchConfig(true);
|
||||
} catch (error) {
|
||||
console.warn('获取系统配置失败:', error);
|
||||
}
|
||||
|
||||
// 获取用户权限码(可选,如果接口不存在则跳过)
|
||||
try {
|
||||
const accessCodes = await getAccessCodesApi();
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { PageQueryDTO } from '#/types/common';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import { getImportTaskPageApi } from '#/api/ec/import/task';
|
||||
@@ -114,7 +115,11 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
||||
unsubAllDone = null;
|
||||
}
|
||||
|
||||
/** 登录后才拉任务列表并订阅 SSE */
|
||||
async function init() {
|
||||
if (!useAccessStore().accessToken) {
|
||||
return;
|
||||
}
|
||||
subscribeRealtime();
|
||||
await fetchTasks(true);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from './auth';
|
||||
export * from './app-config';
|
||||
export * from './col-sidebar-layout';
|
||||
export * from './import-task';
|
||||
export * from './realtime';
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
* 统一文件上传工具
|
||||
* 通过统一文件系统(batchSignUrl)直传 OSS,文件记录自动入库
|
||||
*/
|
||||
import { batchCreateOssFilesApi, batchSignUrlApi } from '#/api/sys/file';
|
||||
|
||||
interface UploadResult {
|
||||
/** 文件访问URL(可直接用于 img src 等) */
|
||||
accessUrl: string;
|
||||
/** 存储路径(用于系统内引用) */
|
||||
storagePath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传单个文件到 OSS(通过统一文件系统)
|
||||
* @param file 文件对象
|
||||
* @param dir 保存目录,如 'product-images', 'shop-logos'
|
||||
*/
|
||||
export async function uploadFileToOssFromSystem(
|
||||
file: File,
|
||||
dir: string = 'general',
|
||||
): Promise<UploadResult> {
|
||||
const signRes = await batchSignUrlApi({
|
||||
files: [{ filename: file.name, fileHash: '' }],
|
||||
});
|
||||
|
||||
const fileInfo = signRes.files[0];
|
||||
if (!fileInfo) {
|
||||
throw new Error('签名响应为空');
|
||||
}
|
||||
|
||||
// 已存在则直接返回
|
||||
if (fileInfo.exists && fileInfo.accessUrl && fileInfo.storagePath) {
|
||||
return {
|
||||
accessUrl: fileInfo.accessUrl,
|
||||
storagePath: fileInfo.storagePath,
|
||||
};
|
||||
}
|
||||
|
||||
// 前端直传 OSS
|
||||
if (fileInfo.uploadUrl && fileInfo.uploadHeaders) {
|
||||
await fetch(fileInfo.uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: fileInfo.uploadHeaders,
|
||||
body: file,
|
||||
});
|
||||
}
|
||||
|
||||
// 通知后端创建文件记录
|
||||
const createRes = await batchCreateOssFilesApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash: '',
|
||||
storagePath: fileInfo.storagePath || '',
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: dir,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const firstFile = createRes[0];
|
||||
if (!firstFile) {
|
||||
throw new Error('文件记录创建失败');
|
||||
}
|
||||
|
||||
return {
|
||||
accessUrl: firstFile.accessUrl || '',
|
||||
storagePath: firstFile.storagePath || '',
|
||||
};
|
||||
}
|
||||
@@ -1,295 +1,10 @@
|
||||
/**
|
||||
* OSS文件上传工具
|
||||
* @deprecated 请使用 `#/utils/upload-file` 的 `uploadFile` / `uploadFiles`
|
||||
*/
|
||||
|
||||
import type { FileVO } from '#/api/sys/file/types';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import SparkMD5 from 'spark-md5';
|
||||
|
||||
import { batchCreateOssFilesApi, batchSignUrlApi } from '#/api/sys/file';
|
||||
|
||||
/**
|
||||
* 上传选项
|
||||
*/
|
||||
export interface UploadOptions {
|
||||
/** 文件分类 */
|
||||
category?: string;
|
||||
/** 错误提示消息 */
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文件的MD5哈希值(使用 spark-md5,支持大文件分片计算)
|
||||
* @param file 文件对象
|
||||
* @returns 返回文件的MD5哈希值(十六进制字符串)
|
||||
*/
|
||||
function calculateFileHash(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const spark = new SparkMD5.ArrayBuffer();
|
||||
const chunkSize = 2 * 1024 * 1024; // 2MB per chunk
|
||||
let offset = 0;
|
||||
|
||||
function loadNext() {
|
||||
const slice = file.slice(offset, offset + chunkSize);
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = (e) => {
|
||||
spark.append(e.target?.result as ArrayBuffer);
|
||||
offset += chunkSize;
|
||||
if (offset < file.size) {
|
||||
loadNext();
|
||||
} else {
|
||||
resolve(spark.end());
|
||||
}
|
||||
};
|
||||
|
||||
reader.onerror = () => reject(new Error('文件哈希计算失败'));
|
||||
reader.readAsArrayBuffer(slice);
|
||||
}
|
||||
|
||||
loadNext();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用Header签名上传文件到OSS
|
||||
* @param file 要上传的文件
|
||||
* @param uploadUrl 上传URL(不含签名参数)
|
||||
* @param uploadHeaders Header签名信息(包含Authorization、Date、x-oss-date、Content-Type等)
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
async function uploadFileToOssWithHeaderSignature(
|
||||
file: File,
|
||||
uploadUrl: string,
|
||||
uploadHeaders: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const headers: Record<string, string> = { ...uploadHeaders };
|
||||
const contentType =
|
||||
headers['Content-Type'] ?? headers['content-type'] ?? '';
|
||||
|
||||
// OSS4 预签名 PUT 与 Content-Type 严格一致;File 作 body 时浏览器会按 file.type 自动带头,易 403。
|
||||
const body =
|
||||
contentType !== '' ? await file.arrayBuffer() : file;
|
||||
if (contentType !== '') {
|
||||
headers['Content-Type'] = contentType;
|
||||
delete headers['content-type'];
|
||||
}
|
||||
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
detail = (await response.text()).slice(0, 300);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(
|
||||
`上传失败: ${response.status} ${response.statusText}${detail ? ` — ${detail}` : ''}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到OSS(通过Header签名)
|
||||
* @param file 要上传的文件
|
||||
* @param options 上传选项
|
||||
* @param options.category 文件分类
|
||||
* @param options.errorMessage 错误提示消息
|
||||
* @returns 返回文件信息,包含文件ID
|
||||
*/
|
||||
export async function uploadFileToOss(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
try {
|
||||
// 1. 计算文件哈希值
|
||||
const fileHash = await calculateFileHash(file);
|
||||
|
||||
// 2. 获取Header签名
|
||||
const signResponse = await batchSignUrlApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!signResponse.files || signResponse.files.length === 0) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
const signInfo = signResponse.files[0];
|
||||
if (!signInfo) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
// 3. 如果文件已存在,直接返回文件信息
|
||||
if (signInfo.exists && signInfo.fileInfo) {
|
||||
return signInfo.fileInfo;
|
||||
}
|
||||
|
||||
// 4. 如果文件不存在,使用Header签名上传到OSS
|
||||
if (!signInfo.uploadUrl) {
|
||||
throw new Error('未获取到上传URL');
|
||||
}
|
||||
if (!signInfo.uploadHeaders) {
|
||||
throw new Error('未获取到上传Header签名信息');
|
||||
}
|
||||
|
||||
await uploadFileToOssWithHeaderSignature(
|
||||
file,
|
||||
signInfo.uploadUrl,
|
||||
signInfo.uploadHeaders,
|
||||
);
|
||||
|
||||
// 5. 上传成功后,创建OSS文件记录
|
||||
// 使用签名响应中的 storagePath
|
||||
if (!signInfo.storagePath) {
|
||||
throw new Error('未获取到存储路径');
|
||||
}
|
||||
|
||||
const createResponse = await batchCreateOssFilesApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
storagePath: signInfo.storagePath,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: options?.category,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!createResponse || createResponse.length === 0) {
|
||||
throw new Error('创建文件记录失败');
|
||||
}
|
||||
|
||||
const fileInfo = createResponse[0];
|
||||
if (!fileInfo) {
|
||||
throw new Error('创建文件记录失败');
|
||||
}
|
||||
|
||||
return fileInfo;
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
const errorMsg = options?.errorMessage || '文件上传失败';
|
||||
message.error(errorMsg);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上传文件到OSS(通过Header签名)
|
||||
* @param files 要上传的文件列表
|
||||
* @param options 上传选项
|
||||
* @param options.category 文件分类
|
||||
* @param options.errorMessage 错误提示消息
|
||||
* @returns 返回文件信息列表
|
||||
*/
|
||||
export async function uploadFilesToOss(
|
||||
files: File[],
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info[]> {
|
||||
try {
|
||||
// 1. 计算所有文件的哈希值
|
||||
const fileItems = await Promise.all(
|
||||
files.map(async (file) => ({
|
||||
filename: file.name,
|
||||
fileHash: await calculateFileHash(file),
|
||||
})),
|
||||
);
|
||||
|
||||
// 2. 批量获取Header签名
|
||||
const signResponse = await batchSignUrlApi({
|
||||
files: fileItems,
|
||||
});
|
||||
|
||||
if (!signResponse.files || signResponse.files.length === 0) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
const results: FileVO.Info[] = [];
|
||||
const filesToUpload: Array<{
|
||||
file: File;
|
||||
fileHash: string;
|
||||
signInfo: FileVO.FileSignInfo;
|
||||
}> = [];
|
||||
|
||||
// 3. 分类处理:已存在的文件和需要上传的文件
|
||||
for (let i = 0; i < signResponse.files.length; i++) {
|
||||
const signInfo = signResponse.files[i];
|
||||
const file = files[i];
|
||||
const fileItem = fileItems[i];
|
||||
if (!signInfo || !file || !fileItem) continue;
|
||||
|
||||
if (signInfo.exists && signInfo.fileInfo) {
|
||||
// 文件已存在,直接使用
|
||||
results.push(signInfo.fileInfo);
|
||||
} else if (signInfo.uploadUrl && signInfo.uploadHeaders) {
|
||||
// 文件不存在,需要上传
|
||||
filesToUpload.push({
|
||||
file,
|
||||
fileHash: fileItem.fileHash,
|
||||
signInfo,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 批量上传不存在的文件
|
||||
if (filesToUpload.length > 0) {
|
||||
await Promise.all(
|
||||
filesToUpload.map(({ file, signInfo }) => {
|
||||
if (!signInfo.uploadUrl) {
|
||||
throw new Error('未获取到上传URL');
|
||||
}
|
||||
if (!signInfo.uploadHeaders) {
|
||||
throw new Error('未获取到上传Header签名信息');
|
||||
}
|
||||
return uploadFileToOssWithHeaderSignature(
|
||||
file,
|
||||
signInfo.uploadUrl,
|
||||
signInfo.uploadHeaders,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// 5. 批量创建OSS文件记录
|
||||
const createResponse = await batchCreateOssFilesApi({
|
||||
files: filesToUpload.map(({ file, signInfo, fileHash }) => {
|
||||
// 使用签名响应中的 storagePath
|
||||
if (!signInfo.storagePath) {
|
||||
throw new Error('未获取到存储路径');
|
||||
}
|
||||
return {
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
storagePath: signInfo.storagePath,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: options?.category,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
if (createResponse && createResponse.length > 0) {
|
||||
results.push(...createResponse);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
const errorMsg = options?.errorMessage || '文件上传失败';
|
||||
message.error(errorMsg);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export {
|
||||
uploadFile as uploadFileToOss,
|
||||
uploadFiles as uploadFilesToOss,
|
||||
uploadFile,
|
||||
uploadFiles,
|
||||
} from './upload-file';
|
||||
export type { UploadOptions } from './upload-file';
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* 统一文件上传:按系统配置在 multipart(后端)与 direct(OSS 直传)间分流
|
||||
*/
|
||||
import type { FileVO } from '#/api/sys/file/types';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
import SparkMD5 from 'spark-md5';
|
||||
|
||||
import {
|
||||
batchCreateOssFilesApi,
|
||||
batchSignUrlApi,
|
||||
batchUploadFilesApi,
|
||||
} from '#/api/sys/file';
|
||||
import { useAppConfigStore } from '#/store/app-config';
|
||||
|
||||
export interface UploadOptions {
|
||||
/** 文件分类 */
|
||||
category?: string;
|
||||
/** 错误提示消息 */
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
function calculateFileHash(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const spark = new SparkMD5.ArrayBuffer();
|
||||
const chunkSize = 2 * 1024 * 1024;
|
||||
let offset = 0;
|
||||
|
||||
function loadNext() {
|
||||
const slice = file.slice(offset, offset + chunkSize);
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
spark.append(e.target?.result as ArrayBuffer);
|
||||
offset += chunkSize;
|
||||
if (offset < file.size) {
|
||||
loadNext();
|
||||
} else {
|
||||
resolve(spark.end());
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('文件哈希计算失败'));
|
||||
reader.readAsArrayBuffer(slice);
|
||||
}
|
||||
|
||||
loadNext();
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadFileToOssWithHeaderSignature(
|
||||
file: File,
|
||||
uploadUrl: string,
|
||||
uploadHeaders: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const headers: Record<string, string> = { ...uploadHeaders };
|
||||
const contentType =
|
||||
headers['Content-Type'] ?? headers['content-type'] ?? '';
|
||||
|
||||
// OSS4 预签名 PUT 与 Content-Type 严格一致
|
||||
const body = contentType !== '' ? await file.arrayBuffer() : file;
|
||||
if (contentType !== '') {
|
||||
headers['Content-Type'] = contentType;
|
||||
delete headers['content-type'];
|
||||
}
|
||||
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
detail = (await response.text()).slice(0, 300);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(
|
||||
`上传失败: ${response.status} ${response.statusText}${detail ? ` — ${detail}` : ''}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** multipart:经后端落盘/对象存储 */
|
||||
async function uploadViaMultipart(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
const uploaded = await batchUploadFilesApi([file], options?.category);
|
||||
const first = uploaded[0];
|
||||
if (!first) {
|
||||
throw new Error('文件上传失败');
|
||||
}
|
||||
return {
|
||||
id: first.id,
|
||||
storageType: first.storageType,
|
||||
storagePath: first.storagePath,
|
||||
filename: first.filename,
|
||||
fileFormat: first.fileFormat,
|
||||
mimeType: first.mimeType,
|
||||
fileSize: first.fileSize,
|
||||
fileHash: first.fileHash,
|
||||
category: first.category,
|
||||
tags: first.tags,
|
||||
remark: first.remark,
|
||||
accessUrl: first.accessUrl,
|
||||
uploadTime: '',
|
||||
updateTime: '',
|
||||
};
|
||||
}
|
||||
|
||||
/** direct:签名直传 OSS 后入库 */
|
||||
async function uploadViaDirect(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
const fileHash = await calculateFileHash(file);
|
||||
const signResponse = await batchSignUrlApi({
|
||||
files: [{ filename: file.name, fileHash }],
|
||||
});
|
||||
|
||||
const signInfo = signResponse.files?.[0];
|
||||
if (!signInfo) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
if (signInfo.exists && signInfo.fileInfo) {
|
||||
return signInfo.fileInfo;
|
||||
}
|
||||
|
||||
if (!signInfo.uploadUrl) {
|
||||
throw new Error('未获取到上传URL');
|
||||
}
|
||||
if (!signInfo.uploadHeaders) {
|
||||
throw new Error('未获取到上传Header签名信息');
|
||||
}
|
||||
if (!signInfo.storagePath) {
|
||||
throw new Error('未获取到存储路径');
|
||||
}
|
||||
|
||||
await uploadFileToOssWithHeaderSignature(
|
||||
file,
|
||||
signInfo.uploadUrl,
|
||||
signInfo.uploadHeaders,
|
||||
);
|
||||
|
||||
const createResponse = await batchCreateOssFilesApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
storagePath: signInfo.storagePath,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: options?.category,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const fileInfo = createResponse?.[0];
|
||||
if (!fileInfo) {
|
||||
throw new Error('创建文件记录失败');
|
||||
}
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传单个文件(按系统配置自动选择 multipart / direct)
|
||||
*/
|
||||
export async function uploadFile(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
try {
|
||||
const appConfig = useAppConfigStore();
|
||||
await appConfig.ensureLoaded();
|
||||
|
||||
if (appConfig.isDirectUpload) {
|
||||
return await uploadViaDirect(file, options);
|
||||
}
|
||||
return await uploadViaMultipart(file, options);
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
message.error(options?.errorMessage || '文件上传失败');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上传(当前按文件串行,保持与单文件同一分流逻辑)
|
||||
*/
|
||||
export async function uploadFiles(
|
||||
files: File[],
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info[]> {
|
||||
const results: FileVO.Info[] = [];
|
||||
for (const file of files) {
|
||||
results.push(await uploadFile(file, options));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 uploadFile */
|
||||
export const uploadFileToOss = uploadFile;
|
||||
/** @deprecated 使用 uploadFiles */
|
||||
export const uploadFilesToOss = uploadFiles;
|
||||
+2
-2
@@ -20,7 +20,7 @@ import { getAdFeeFieldsApi } from '#/api/ec/shop/ad-fee/apis';
|
||||
import { getShopPageApi } from '#/api/ec/shop';
|
||||
import { createImportTaskApi } from '#/api/ec/import/task';
|
||||
import { useImportTaskStore } from '#/store';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface FieldMappingItem {
|
||||
@@ -430,7 +430,7 @@ const handleCreateTask = async () => {
|
||||
createTaskSubmitting.value = true;
|
||||
message.loading('正在上传文件...', 0);
|
||||
const patchedFile = buildPatchedCsv();
|
||||
const fileInfo = await uploadFileToOss(patchedFile, {
|
||||
const fileInfo = await uploadFile(patchedFile, {
|
||||
category: 'ad-fee-import',
|
||||
errorMessage: '文件上传失败,请重试',
|
||||
});
|
||||
|
||||
+2
-2
@@ -34,7 +34,7 @@ import { createImportTaskApi } from '#/api/ec/import/task';
|
||||
import { getAllOrderStatusListApi } from '#/api/ec/order/status';
|
||||
import { getShopPageApi } from '#/api/ec/shop';
|
||||
import { useImportTaskStore } from '#/store';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import { createPatchedFile } from '../utils/skuCodePatch';
|
||||
|
||||
// 定义映射项数据结构
|
||||
@@ -1179,7 +1179,7 @@ const handleCreateTask = async () => {
|
||||
|
||||
// 先上传文件到 OSS(使用统一文件系统)
|
||||
message.loading('正在上传文件...', 0);
|
||||
const fileInfo = await uploadFileToOss(selectedFile.value, {
|
||||
const fileInfo = await uploadFile(selectedFile.value, {
|
||||
category: 'order-import',
|
||||
errorMessage: '文件上传失败,请重试',
|
||||
});
|
||||
|
||||
+3
-3
@@ -21,7 +21,7 @@ import dayjs from 'dayjs';
|
||||
|
||||
import { getCategoryTreeApi } from '#/api/ec/product/category';
|
||||
import { createProductApi, updateProductApi } from '#/api/ec/product';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
|
||||
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
|
||||
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
|
||||
@@ -873,7 +873,7 @@ async function uploadImageAndGetId(): Promise<number | undefined> {
|
||||
}
|
||||
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(newImageFile.value, {
|
||||
const fileInfo = await uploadFile(newImageFile.value, {
|
||||
category: 'product-main-image',
|
||||
errorMessage: '主图上传失败',
|
||||
});
|
||||
@@ -886,7 +886,7 @@ async function uploadImageAndGetId(): Promise<number | undefined> {
|
||||
|
||||
async function uploadSkuImageAndGetId(file: File): Promise<number | undefined> {
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(file, {
|
||||
const fileInfo = await uploadFile(file, {
|
||||
category: 'product-sku-image',
|
||||
errorMessage: 'SKU 图片上传失败',
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Button, Form, Input, message, Select } from 'ant-design-vue';
|
||||
|
||||
import { createShopApi, updateShopApi } from '#/api/ec/shop';
|
||||
import { getPlatformListApi } from '#/api/ec/platform';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
@@ -239,7 +239,7 @@ async function uploadLogoAndGetId(): Promise<number | undefined> {
|
||||
}
|
||||
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(newLogoFile.value, {
|
||||
const fileInfo = await uploadFile(newLogoFile.value, {
|
||||
category: 'shop-logo',
|
||||
errorMessage: 'Logo上传失败',
|
||||
});
|
||||
|
||||
+6
-4
@@ -19,8 +19,8 @@ import dayjs from 'dayjs';
|
||||
import {
|
||||
createCompanyApi,
|
||||
updateCompanyApi,
|
||||
uploadCompanyLogoApi,
|
||||
} from '#/api/company';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
@@ -271,11 +271,13 @@ async function uploadLogoAndGetId(): Promise<number | undefined> {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await uploadCompanyLogoApi(newLogoFile.value);
|
||||
return response.id;
|
||||
const fileInfo = await uploadFile(newLogoFile.value, {
|
||||
category: 'company-logo',
|
||||
errorMessage: 'Logo上传失败',
|
||||
});
|
||||
return fileInfo.id;
|
||||
} catch (error) {
|
||||
console.error('Logo上传失败:', error);
|
||||
message.error('Logo上传失败');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Page } from '@vben/common-ui';
|
||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||
|
||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
defineOptions({ name: 'PersonalProfile' });
|
||||
|
||||
@@ -87,7 +87,7 @@ async function handleSubmit() {
|
||||
if (pendingAvatarFile.value) {
|
||||
avatarLoading.value = true;
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(pendingAvatarFile.value, {
|
||||
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
||||
category: 'user-avatar',
|
||||
errorMessage: '头像上传失败',
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user