mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 04:29:21 +08:00
160 lines
6.1 KiB
Java
160 lines
6.1 KiB
Java
package top.xyquan.pocketdgcuservice.service.impl;
|
|
|
|
import com.aliyun.oss.OSS;
|
|
import com.aliyun.oss.OSSClientBuilder;
|
|
import jakarta.annotation.PreDestroy;
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.util.StringUtils;
|
|
import top.xyquan.pocketdgcuservice.config.OSSConfig;
|
|
import top.xyquan.pocketdgcuservice.domain.dto.OssHeaderSignDTO;
|
|
import top.xyquan.pocketdgcuservice.domain.vo.OssHeaderSignVO;
|
|
|
|
import javax.crypto.Mac;
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
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.*;
|
|
import java.util.stream.Collectors;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class OssService {
|
|
|
|
private final OSSConfig ossConfig;
|
|
private OSS ossClient; // OSSClient实例
|
|
|
|
// 批量生成OssHeaderSignVO
|
|
public List<OssHeaderSignVO> generateBulkUploadHeaderSigns(String belongTo, List<OssHeaderSignDTO> dtos) {
|
|
Map<String, String> dirMap = new HashMap<>();
|
|
dirMap.put("post", "pocket-dgcu/post-images");
|
|
dirMap.put("chat", "pocket-dgcu/chat-images");
|
|
dirMap.put("avatar", "pocket-dgcu/avatars");
|
|
dirMap.put("auth", "pocket-dgcu/auth-images");
|
|
|
|
String dir = dirMap.getOrDefault(belongTo, "pocket-dgcu/default");
|
|
|
|
return dtos
|
|
.stream()
|
|
.map(dto -> generateUploadHeaderSign(dir, dto)
|
|
)
|
|
.collect(Collectors.toList());
|
|
}
|
|
|
|
// 批量删除文件
|
|
public void deleteFiles(List<String> urlList) {
|
|
OSS ossClient = getOssClient();
|
|
urlList.forEach(url -> {
|
|
try {
|
|
String fullPath = url
|
|
.substring(url.lastIndexOf("aliyuncs.com/") + "aliyuncs.com/".length());
|
|
ossClient.deleteObject(ossConfig.getBucketName(), fullPath);
|
|
} catch (Exception e) {
|
|
// 忽略所有异常
|
|
}
|
|
});
|
|
}
|
|
|
|
// 获取OSSClient实例(懒加载)
|
|
private OSS getOssClient() {
|
|
if (ossClient == null) {
|
|
synchronized (this) {
|
|
if (ossClient == null) {
|
|
// 初始化OSSClient
|
|
ossClient = new OSSClientBuilder()
|
|
.build(ossConfig.getEndPoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
|
|
}
|
|
}
|
|
}
|
|
return ossClient;
|
|
}
|
|
|
|
// 关闭OSSClient(在应用关闭时调用)
|
|
@PreDestroy
|
|
public void shutdown() {
|
|
if (ossClient != null) {
|
|
ossClient.shutdown();
|
|
}
|
|
}
|
|
|
|
// 生成单个OssHeaderSignVO
|
|
private OssHeaderSignVO generateUploadHeaderSign(String dir, OssHeaderSignDTO dto) {
|
|
// 生成UUID并拼接文件名
|
|
String uuidFileName = generateUUIDFileName(dto.getFileName());
|
|
|
|
// 生成签名头信息
|
|
Map<String, String> headers = generateUploadHeaders(dir, uuidFileName, dto.getContentType());
|
|
|
|
// 构建OssHeaderSignVO对象
|
|
OssHeaderSignVO vo = new OssHeaderSignVO();
|
|
vo.setFileName(dto.getFileName()); // 设置拼接后的文件名
|
|
vo.setSignUrl(buildObjectUrl(dir, uuidFileName)); // 设置完整URL
|
|
vo.setAuthorization(headers.get("Authorization")); // 设置Authorization签名
|
|
vo.setContentType(dto.getContentType()); // 设置ContentType
|
|
|
|
return vo;
|
|
}
|
|
|
|
// 生成UUID拼接文件名
|
|
private String generateUUIDFileName(String fileName) {
|
|
String uuid = UUID.randomUUID().toString().replace("-", ""); // 生成UUID并去除横线
|
|
return uuid + "_" + fileName; // 拼接为 uuid_filename 格式
|
|
}
|
|
|
|
// 生成上传所需的Header签名(内部方法)
|
|
private Map<String, String> generateUploadHeaders(String dir, String fileName, String contentType) {
|
|
String httpMethod = "PUT";
|
|
String date = getCurrentUTCDate();
|
|
String canonicalizedResource = "/" + ossConfig.getBucketName() + "/" + dir + "/" + fileName;
|
|
|
|
String stringToSign = buildStringToSign(httpMethod, "", contentType, date, canonicalizedResource);
|
|
String signature = calculateSignature(stringToSign, ossConfig.getAccessKeySecret());
|
|
String authorization = "OSS " + ossConfig.getAccessKeyId() + ":" + signature;
|
|
|
|
Map<String, String> headers = new HashMap<>();
|
|
headers.put("Authorization", authorization);
|
|
headers.put("Date", date);
|
|
if (StringUtils.hasText(contentType)) {
|
|
headers.put("Content-Type", contentType);
|
|
}
|
|
return headers;
|
|
}
|
|
|
|
// 构建对象访问URL
|
|
private String buildObjectUrl(String dir, String fileName) {
|
|
return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndPoint() + "/" + dir + "/" + fileName;
|
|
}
|
|
|
|
// 获取当前UTC时间(RFC 1123格式)
|
|
private String getCurrentUTCDate() {
|
|
return ZonedDateTime.now(ZoneOffset.UTC)
|
|
.format(DateTimeFormatter.RFC_1123_DATE_TIME);
|
|
}
|
|
|
|
// 构建待签名字符串
|
|
private String buildStringToSign(String httpMethod, String contentMD5, String contentType,
|
|
String date, String canonicalizedResource) {
|
|
return String.join("\n",
|
|
httpMethod,
|
|
contentMD5,
|
|
contentType,
|
|
date,
|
|
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);
|
|
}
|
|
}
|
|
} |