mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 10:29:19 +08:00
1
This commit is contained in:
+56
-1
@@ -2,6 +2,9 @@ package top.xyquan.ecomdmbbackend.modules.sys.config;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.ClientBuilderConfiguration;
|
||||
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
|
||||
import com.aliyun.oss.common.comm.SignVersion;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -34,7 +37,29 @@ public class OssConfig {
|
||||
accessKeySecret == null || accessKeySecret.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
|
||||
String region = getRegion();
|
||||
|
||||
// 如果无法提取region,使用默认方式创建(V1签名)
|
||||
if (region == null || region.isEmpty()) {
|
||||
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
}
|
||||
|
||||
// 使用V4签名版本创建OSSClient(参考官方示例)
|
||||
// V4签名对时区容错性更好,推荐用于预签名URL
|
||||
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
|
||||
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
|
||||
|
||||
// 创建CredentialsProvider(参考官方示例)
|
||||
DefaultCredentialProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
|
||||
|
||||
// 按照官方示例的方式创建OSSClient
|
||||
return OSSClientBuilder.create()
|
||||
.endpoint(endpoint)
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.clientConfiguration(clientBuilderConfiguration)
|
||||
.region(region)
|
||||
.build();
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
@@ -48,5 +73,35 @@ public class OssConfig {
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() {
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
public String getAccessKeySecret() {
|
||||
return accessKeySecret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从endpoint提取region
|
||||
* 例如:oss-cn-hangzhou.aliyuncs.com -> cn-hangzhou
|
||||
* oss-cn-guangzhou.aliyuncs.com -> cn-guangzhou
|
||||
*/
|
||||
public String getRegion() {
|
||||
if (endpoint == null || endpoint.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String endpointWithoutProtocol = endpoint.replace("https://", "").replace("http://", "");
|
||||
// 格式:oss-cn-{region}.aliyuncs.com
|
||||
if (endpointWithoutProtocol.startsWith("oss-cn-")) {
|
||||
int start = "oss-cn-".length();
|
||||
int end = endpointWithoutProtocol.indexOf(".aliyuncs.com");
|
||||
if (end > start) {
|
||||
return "cn-" + endpointWithoutProtocol.substring(start, end);
|
||||
}
|
||||
}
|
||||
// 如果格式不匹配,尝试其他格式
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-1
@@ -5,9 +5,12 @@ 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.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
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.dto.file.SysFileFilterDTO;
|
||||
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;
|
||||
@@ -36,7 +39,7 @@ public class SysFileController {
|
||||
return ApiResponse.success(result);
|
||||
}
|
||||
|
||||
@Operation(summary = "批量获取URL签名", description = "批量获取OSS文件上传URL签名,如果文件已存在则返回文件信息")
|
||||
@Operation(summary = "批量获取Header签名", description = "批量获取OSS文件上传Header签名(V1签名方式,HMAC-SHA1),如果文件已存在则返回文件信息")
|
||||
@PostMapping("/batch-sign-url")
|
||||
public ApiResponse<BatchSignUrlVO> batchSignUrl(@Valid @RequestBody BatchSignUrlDTO dto) {
|
||||
BatchSignUrlVO result = sysFileService.batchSignUrl(dto);
|
||||
@@ -56,5 +59,12 @@ public class SysFileController {
|
||||
String accessUrl = sysFileService.getFileAccessUrl(fileId);
|
||||
return ApiResponse.success(accessUrl);
|
||||
}
|
||||
|
||||
@Operation(summary = "分页获取文件列表", description = "分页获取当前公司的文件列表,支持条件过滤")
|
||||
@PostMapping("/page")
|
||||
public ApiResponse<PageResultVO<SysFileVO>> getFilePage(@Valid @RequestBody PageQueryDTO<SysFileFilterDTO> pageQueryDTO) {
|
||||
PageResultVO<SysFileVO> result = sysFileService.getFilePage(pageQueryDTO);
|
||||
return ApiResponse.success(result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.file;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 系统文件分页查询过滤DTO
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "系统文件分页查询过滤DTO")
|
||||
public class SysFileFilterDTO {
|
||||
|
||||
/**
|
||||
* 文件名(模糊查询)
|
||||
*/
|
||||
@Schema(description = "文件名(模糊查询)", example = "logo")
|
||||
private String filename;
|
||||
|
||||
/**
|
||||
* 文件格式(精准查询)
|
||||
*/
|
||||
@Schema(description = "文件格式(精准查询)", example = "jpg")
|
||||
private String fileFormat;
|
||||
|
||||
/**
|
||||
* 存储类型(精准查询)
|
||||
*/
|
||||
@Schema(description = "存储类型(精准查询)", example = "oss", allowableValues = {"local", "oss", "s3", "qiniu", "cos"})
|
||||
private String storageType;
|
||||
|
||||
/**
|
||||
* 文件分类(精准查询)
|
||||
*/
|
||||
@Schema(description = "文件分类(精准查询)", example = "image")
|
||||
private String category;
|
||||
|
||||
/**
|
||||
* 标签(模糊查询)
|
||||
*/
|
||||
@Schema(description = "标签(模糊查询)", example = "logo")
|
||||
private String tags;
|
||||
|
||||
/**
|
||||
* 上传时间范围-开始时间
|
||||
*/
|
||||
@Schema(description = "上传时间范围-开始时间", example = "2024-01-01T00:00:00")
|
||||
private LocalDateTime startUploadTime;
|
||||
|
||||
/**
|
||||
* 上传时间范围-结束时间
|
||||
*/
|
||||
@Schema(description = "上传时间范围-结束时间", example = "2024-12-31T23:59:59")
|
||||
private LocalDateTime endUploadTime;
|
||||
}
|
||||
|
||||
+10
-3
@@ -4,12 +4,13 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 批量URL签名响应VO
|
||||
* 批量Header签名响应VO(Header签名)
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "批量URL签名响应VO")
|
||||
@Schema(description = "批量Header签名响应VO(Header签名)")
|
||||
public class BatchSignUrlVO {
|
||||
|
||||
@Schema(description = "文件信息列表")
|
||||
@@ -33,9 +34,15 @@ public class BatchSignUrlVO {
|
||||
@Schema(description = "是否已存在", example = "true")
|
||||
private Boolean exists;
|
||||
|
||||
@Schema(description = "上传URL(如果文件不存在,用于前端上传)", example = "https://oss.example.com/upload?signature=xxx")
|
||||
@Schema(description = "上传URL(如果文件不存在,不含签名参数)", example = "https://bucket.oss-cn-hangzhou.aliyuncs.com/uploads/2024/01/file.jpg")
|
||||
private String uploadUrl;
|
||||
|
||||
@Schema(description = "上传所需的Header签名信息(如果文件不存在,包含Authorization、Date、x-oss-date、Content-Type等)", example = "{\"Authorization\":\"OSS xxx:xxx\",\"Date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"x-oss-date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"Content-Type\":\"image/jpeg\"}")
|
||||
private Map<String, String> uploadHeaders;
|
||||
|
||||
@Schema(description = "存储路径/Key(如果文件不存在,用于前端创建文件记录时使用)", example = "uploads/2024/01/abc123def456.jpg")
|
||||
private String storagePath;
|
||||
|
||||
@Schema(description = "访问URL(如果文件已存在,临时签名URL)", example = "https://oss.example.com/file.jpg?signature=xxx")
|
||||
private String accessUrl;
|
||||
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OSS Header签名信息VO(V1签名方式)
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "OSS Header签名信息VO(V1签名方式)")
|
||||
public class OssPostPolicyVO {
|
||||
|
||||
@Schema(description = "OSS上传URL(不含签名参数,前端需要使用Header签名上传)", example = "https://your-bucket.oss-cn-hangzhou.aliyuncs.com/uploads/2024/01/file.jpg")
|
||||
private String url;
|
||||
|
||||
@Schema(description = "存储路径/Key", example = "uploads/2024/01/file.jpg")
|
||||
private String key;
|
||||
|
||||
@Schema(description = "上传所需的Header签名信息(包含Authorization、Date、x-oss-date、Content-Type等)", example = "{\"Authorization\":\"OSS xxx:xxx\",\"Date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"x-oss-date\":\"Mon, 01 Jan 2024 00:00:00 GMT\",\"Content-Type\":\"image/jpeg\"}")
|
||||
private Map<String, String> headers;
|
||||
}
|
||||
|
||||
+6
-4
@@ -1,5 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.OssPostPolicyVO;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
@@ -8,13 +10,13 @@ import java.io.InputStream;
|
||||
public interface OssService {
|
||||
|
||||
/**
|
||||
* 生成上传URL(预签名URL)
|
||||
* 生成上传Header签名(V1签名方式,HMAC-SHA1)
|
||||
*
|
||||
* @param storagePath 存储路径/Key
|
||||
* @param expirationMinutes 过期时间(分钟)
|
||||
* @return 预签名URL
|
||||
* @param expirationMinutes 过期时间(分钟,当前Header签名不使用此参数,保留用于兼容)
|
||||
* @return Header签名信息(包含上传URL和签名headers)
|
||||
*/
|
||||
String generateUploadUrl(String storagePath, int expirationMinutes);
|
||||
OssPostPolicyVO generateUploadPolicy(String storagePath, int expirationMinutes);
|
||||
|
||||
/**
|
||||
* 生成访问URL(预签名URL)
|
||||
|
||||
+20
@@ -1,8 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service;
|
||||
|
||||
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.model.dto.file.BatchCreateOssFileDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.BatchSignUrlDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.file.SysFileFilterDTO;
|
||||
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;
|
||||
@@ -22,6 +25,15 @@ public interface SysFileService {
|
||||
*/
|
||||
List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files);
|
||||
|
||||
/**
|
||||
* 批量上传文件(仅用于本地存储),支持设置文件分类
|
||||
*
|
||||
* @param files 文件列表
|
||||
* @param category 文件分类
|
||||
* @return 文件信息列表(不包含敏感信息)
|
||||
*/
|
||||
List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files, String category);
|
||||
|
||||
/**
|
||||
* 批量获取URL签名(用于前端上传到OSS)
|
||||
*
|
||||
@@ -45,5 +57,13 @@ public interface SysFileService {
|
||||
* @return 文件访问URL
|
||||
*/
|
||||
String getFileAccessUrl(Long fileId);
|
||||
|
||||
/**
|
||||
* 分页获取当前公司的文件列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<SysFileVO> getFilePage(PageQueryDTO<SysFileFilterDTO> pageQueryDTO);
|
||||
}
|
||||
|
||||
|
||||
+213
-11
@@ -1,14 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.HttpMethod;
|
||||
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.model.vo.OssPostPolicyVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.OssService;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OSS服务实现类
|
||||
@@ -25,34 +38,223 @@ public class OssServiceImpl implements OssService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateUploadUrl(String storagePath, int expirationMinutes) {
|
||||
public OssPostPolicyVO generateUploadPolicy(String storagePath, int expirationMinutes) {
|
||||
if (ossClient == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ossConfig.getBucketName() == null || ossConfig.getBucketName().isEmpty() ||
|
||||
storagePath == null || storagePath.isEmpty()) {
|
||||
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();
|
||||
// 根据文件后缀获取Content-Type
|
||||
String contentType = getContentTypeFromPath(storagePath);
|
||||
|
||||
// 生成Header签名(V1签名方式,HMAC-SHA1)
|
||||
Map<String, String> headers = generateUploadHeaders(storagePath, contentType);
|
||||
|
||||
// 构建上传URL(不含签名参数)
|
||||
String uploadUrl = buildObjectUrl(storagePath);
|
||||
|
||||
// 构建返回对象
|
||||
OssPostPolicyVO policyVO = new OssPostPolicyVO();
|
||||
policyVO.setUrl(uploadUrl);
|
||||
policyVO.setKey(storagePath);
|
||||
policyVO.setHeaders(headers);
|
||||
|
||||
return policyVO;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成上传所需的Header签名(V1签名方式,HMAC-SHA1)
|
||||
* 参考官方文档:VERB + "\n" + CONTENT-MD5 + "\n" + CONTENT-TYPE + "\n" + DATE + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
|
||||
* 如果使用x-oss-date,需要在CanonicalizedOSSHeaders中包含
|
||||
*/
|
||||
private Map<String, String> generateUploadHeaders(String storagePath, String contentType) {
|
||||
String httpMethod = "PUT";
|
||||
String date = getCurrentUTCDate(); // RFC 1123格式的UTC时间(GMT)
|
||||
String canonicalizedResource = "/" + ossConfig.getBucketName() + "/" + storagePath;
|
||||
|
||||
// 构建CanonicalizedOSSHeaders,包含x-oss-date(值与Date保持一致)
|
||||
// 格式:header-name:header-value\n(按字典序排序)
|
||||
String canonicalizedOSSHeaders = "x-oss-date:" + date + "\n";
|
||||
|
||||
// 构建StringToSign:VERB + "\n" + CONTENT-MD5 + "\n" + CONTENT-TYPE + "\n" + DATE + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
|
||||
String stringToSign = buildStringToSign(httpMethod, "", contentType != null ? contentType : "", date, canonicalizedOSSHeaders, canonicalizedResource);
|
||||
|
||||
// 计算HMAC-SHA1签名
|
||||
String signature = calculateSignature(stringToSign, ossConfig.getAccessKeySecret());
|
||||
String authorization = "OSS " + ossConfig.getAccessKeyId() + ":" + signature;
|
||||
|
||||
// 构建返回的headers Map
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Authorization", authorization);
|
||||
headers.put("Date", date);
|
||||
headers.put("x-oss-date", date); // x-oss-date值与Date保持一致
|
||||
// 如果contentType为空,使用默认值
|
||||
headers.put("Content-Type", contentType != null && !contentType.isEmpty() ? contentType : "application/octet-stream");
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件路径获取Content-Type
|
||||
* 从文件路径中提取文件扩展名,然后返回对应的MIME类型
|
||||
*/
|
||||
private String getContentTypeFromPath(String storagePath) {
|
||||
if (storagePath == null || storagePath.isEmpty()) {
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
// 提取文件扩展名
|
||||
int lastDotIndex = storagePath.lastIndexOf(".");
|
||||
if (lastDotIndex < 0 || lastDotIndex >= storagePath.length() - 1) {
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
String extension = storagePath.substring(lastDotIndex + 1).toLowerCase();
|
||||
|
||||
// 根据扩展名返回对应的Content-Type
|
||||
return getContentTypeByExtension(extension);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件扩展名获取Content-Type
|
||||
*/
|
||||
private String getContentTypeByExtension(String extension) {
|
||||
if (extension == null || extension.isEmpty()) {
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
// 常见文件类型的MIME类型映射
|
||||
return switch (extension) {
|
||||
// 图片类型
|
||||
case "jpg", "jpeg" -> "image/jpeg";
|
||||
case "png" -> "image/png";
|
||||
case "gif" -> "image/gif";
|
||||
case "bmp" -> "image/bmp";
|
||||
case "webp" -> "image/webp";
|
||||
case "svg" -> "image/svg+xml";
|
||||
case "ico" -> "image/x-icon";
|
||||
|
||||
// 文档类型
|
||||
case "pdf" -> "application/pdf";
|
||||
case "doc" -> "application/msword";
|
||||
case "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
||||
case "xls" -> "application/vnd.ms-excel";
|
||||
case "xlsx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
case "ppt" -> "application/vnd.ms-powerpoint";
|
||||
case "pptx" -> "application/vnd.openxmlformats-officedocument.presentationml.presentation";
|
||||
|
||||
// 文本类型
|
||||
case "txt" -> "text/plain";
|
||||
case "html", "htm" -> "text/html";
|
||||
case "css" -> "text/css";
|
||||
case "js" -> "application/javascript";
|
||||
case "json" -> "application/json";
|
||||
case "xml" -> "application/xml";
|
||||
|
||||
// 压缩文件
|
||||
case "zip" -> "application/zip";
|
||||
case "rar" -> "application/x-rar-compressed";
|
||||
case "7z" -> "application/x-7z-compressed";
|
||||
case "tar" -> "application/x-tar";
|
||||
case "gz" -> "application/gzip";
|
||||
|
||||
// 视频类型
|
||||
case "mp4" -> "video/mp4";
|
||||
case "avi" -> "video/x-msvideo";
|
||||
case "mov" -> "video/quicktime";
|
||||
case "wmv" -> "video/x-ms-wmv";
|
||||
case "flv" -> "video/x-flv";
|
||||
case "webm" -> "video/webm";
|
||||
|
||||
// 音频类型
|
||||
case "mp3" -> "audio/mpeg";
|
||||
case "wav" -> "audio/wav";
|
||||
case "ogg" -> "audio/ogg";
|
||||
case "aac" -> "audio/aac";
|
||||
case "flac" -> "audio/flac";
|
||||
|
||||
// 其他
|
||||
default -> "application/octet-stream";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建对象访问URL(不含签名参数)
|
||||
* 格式:https://bucket-name.endpoint/storagePath
|
||||
*/
|
||||
private String buildObjectUrl(String storagePath) {
|
||||
String endpoint = ossConfig.getEndpoint();
|
||||
// 移除协议前缀(如果有)
|
||||
if (endpoint.startsWith("http://")) {
|
||||
endpoint = endpoint.substring(7);
|
||||
} else if (endpoint.startsWith("https://")) {
|
||||
endpoint = endpoint.substring(8);
|
||||
}
|
||||
// 格式:https://bucket-name.endpoint/storagePath
|
||||
return "https://" + ossConfig.getBucketName() + "." + endpoint + "/" + storagePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前UTC时间(RFC 1123格式)
|
||||
*/
|
||||
private String getCurrentUTCDate() {
|
||||
return ZonedDateTime.now(ZoneOffset.UTC)
|
||||
.format(DateTimeFormatter.RFC_1123_DATE_TIME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建待签名字符串(严格按照官方公式)
|
||||
* 公式:VERB + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
|
||||
* 注意:CanonicalizedOSSHeaders 和 CanonicalizedResource 之间没有 "\n",直接连接
|
||||
*/
|
||||
private String buildStringToSign(String httpMethod, String contentMD5, String contentType,
|
||||
String date, String canonicalizedOSSHeaders, String canonicalizedResource) {
|
||||
// 严格按照官方公式构建:VERB + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + Date + "\n" + CanonicalizedOSSHeaders + CanonicalizedResource
|
||||
return httpMethod + "\n"
|
||||
+ (contentMD5 != null ? contentMD5 : "") + "\n"
|
||||
+ (contentType != null ? contentType : "") + "\n"
|
||||
+ date + "\n"
|
||||
+ canonicalizedOSSHeaders + canonicalizedResource;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算HMAC-SHA1签名
|
||||
*/
|
||||
private String calculateSignature(String stringToSign, String accessKeySecret) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA1");
|
||||
mac.init(new SecretKeySpec(accessKeySecret.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
|
||||
byte[] signature = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(signature);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
throw new RuntimeException("Error calculating signature", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateAccessUrl(String storagePath, int expirationMinutes) {
|
||||
if (ossClient == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Date expiration = new Date(System.currentTimeMillis() + expirationMinutes * 60 * 1000L);
|
||||
// 设置过期时间(参考官方示例:new Date(new Date().getTime() + 3600 * 1000L))
|
||||
Date expiration = new Date(new Date().getTime() + expirationMinutes * 60 * 1000L);
|
||||
|
||||
// 生成预签名URL(GET方法,用于下载,参考官方示例)
|
||||
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
|
||||
ossConfig.getBucketName(), storagePath);
|
||||
ossConfig.getBucketName(), storagePath, HttpMethod.GET);
|
||||
// 设置过期时间
|
||||
request.setExpiration(expiration);
|
||||
request.setMethod(com.aliyun.oss.HttpMethod.GET);
|
||||
|
||||
// 通过HTTP GET请求生成预签名URL
|
||||
URL url = ossClient.generatePresignedUrl(request);
|
||||
return url.toString();
|
||||
} catch (Exception e) {
|
||||
|
||||
+201
-6
@@ -1,17 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
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.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
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.dto.file.SysFileFilterDTO;
|
||||
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.OssPostPolicyVO;
|
||||
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;
|
||||
@@ -24,6 +30,7 @@ import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 系统文件服务实现类
|
||||
@@ -129,6 +136,129 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有找到有效的其他公司文件,或者文件不存在,则作为新文件处理
|
||||
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
|
||||
@Transactional
|
||||
public List<SysFileUploadVO> batchUploadFiles(List<MultipartFile> files, String category) {
|
||||
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)) {
|
||||
// 如果文件已存在但category不同,更新category
|
||||
if (category != null && !category.equals(existingFile.getCategory())) {
|
||||
existingFile.setCategory(category);
|
||||
this.updateById(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.setCategory(category); // 设置文件分类
|
||||
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) {
|
||||
// 没有任何公司有相同文件,生成新的存储路径并上传(仅本地存储)
|
||||
@@ -146,6 +276,7 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
sysFile.setMimeType(file.getContentType());
|
||||
sysFile.setFileSize(file.getSize());
|
||||
sysFile.setFileHash(fileHash);
|
||||
sysFile.setCategory(category); // 设置文件分类
|
||||
sysFile.setUploadBy(userId);
|
||||
|
||||
this.save(sysFile);
|
||||
@@ -231,10 +362,15 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
}
|
||||
|
||||
if (otherCompanyFile == null) {
|
||||
// 文件不存在,返回OSS签名URL(不创建记录)
|
||||
// 文件不存在,返回OSS Header签名信息(不创建记录)
|
||||
signInfo.setExists(false);
|
||||
String storagePath = generateStoragePath(item.getFilename(), item.getFileHash());
|
||||
signInfo.setUploadUrl(ossService.generateUploadUrl(storagePath, 60));
|
||||
OssPostPolicyVO uploadPolicy = ossService.generateUploadPolicy(storagePath, 120);
|
||||
if (uploadPolicy != null && uploadPolicy.getUrl() != null) {
|
||||
signInfo.setUploadUrl(uploadPolicy.getUrl());
|
||||
signInfo.setUploadHeaders(uploadPolicy.getHeaders());
|
||||
signInfo.setStoragePath(storagePath); // 返回storagePath供前端创建文件记录时使用
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,12 +592,71 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
|
||||
SysFileVO vo = new SysFileVO();
|
||||
BeanUtils.copyProperties(sysFile, vo);
|
||||
|
||||
// 如果是OSS存储,生成访问URL
|
||||
if ("oss".equals(sysFile.getStorageType())) {
|
||||
vo.setAccessUrl(ossService.generateAccessUrl(sysFile.getStoragePath(), 60));
|
||||
}
|
||||
// 使用工具类生成访问URL
|
||||
String accessUrl = SysFileUtils.getFileAccessUrl(sysFile.getStoragePath(), sysFile.getStorageType());
|
||||
vo.setAccessUrl(accessUrl);
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<SysFileVO> getFilePage(PageQueryDTO<SysFileFilterDTO> pageQueryDTO) {
|
||||
// 从token中获取公司ID
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
// 创建分页对象
|
||||
Page<SysFilePO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
|
||||
// 构建查询条件
|
||||
LambdaQueryWrapper<SysFilePO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(SysFilePO::getCompanyId, companyId)
|
||||
.isNull(SysFilePO::getDeleteTime); // 只查询未删除的文件
|
||||
|
||||
// 添加过滤条件
|
||||
SysFileFilterDTO filter = pageQueryDTO.getFilters();
|
||||
if (filter != null) {
|
||||
// 文件名(模糊查询)
|
||||
if (filter.getFilename() != null && !filter.getFilename().trim().isEmpty()) {
|
||||
wrapper.like(SysFilePO::getFilename, filter.getFilename());
|
||||
}
|
||||
// 文件格式(精准查询)
|
||||
if (filter.getFileFormat() != null && !filter.getFileFormat().trim().isEmpty()) {
|
||||
wrapper.eq(SysFilePO::getFileFormat, filter.getFileFormat());
|
||||
}
|
||||
// 存储类型(精准查询)
|
||||
if (filter.getStorageType() != null && !filter.getStorageType().trim().isEmpty()) {
|
||||
wrapper.eq(SysFilePO::getStorageType, filter.getStorageType());
|
||||
}
|
||||
// 文件分类(精准查询)
|
||||
if (filter.getCategory() != null && !filter.getCategory().trim().isEmpty()) {
|
||||
wrapper.eq(SysFilePO::getCategory, filter.getCategory());
|
||||
}
|
||||
// 标签(模糊查询)
|
||||
if (filter.getTags() != null && !filter.getTags().trim().isEmpty()) {
|
||||
wrapper.like(SysFilePO::getTags, filter.getTags());
|
||||
}
|
||||
// 上传时间范围
|
||||
if (filter.getStartUploadTime() != null) {
|
||||
wrapper.ge(SysFilePO::getUploadTime, filter.getStartUploadTime());
|
||||
}
|
||||
if (filter.getEndUploadTime() != null) {
|
||||
wrapper.le(SysFilePO::getUploadTime, filter.getEndUploadTime());
|
||||
}
|
||||
}
|
||||
|
||||
// 排序:按上传时间倒序
|
||||
wrapper.orderByDesc(SysFilePO::getUploadTime);
|
||||
|
||||
// 执行分页查询
|
||||
IPage<SysFilePO> pageResult = this.page(page, wrapper);
|
||||
|
||||
// 转换为VO并生成访问URL
|
||||
List<SysFileVO> voList = pageResult.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 构建分页结果
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user