|
|
@@ -0,0 +1,167 @@
|
|
|
+package com.train.service.impl;
|
|
|
+
|
|
|
+import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
|
|
+import com.amazonaws.auth.BasicAWSCredentials;
|
|
|
+import com.amazonaws.services.s3.AmazonS3;
|
|
|
+import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
|
|
+import com.amazonaws.services.s3.model.ObjectMetadata;
|
|
|
+import com.amazonaws.services.s3.model.PutObjectRequest;
|
|
|
+import com.train.service.StorageService;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import javax.annotation.PostConstruct;
|
|
|
+import java.io.ByteArrayInputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import java.net.URI;
|
|
|
+import java.time.LocalDate;
|
|
|
+import java.time.format.DateTimeFormatter;
|
|
|
+import java.util.UUID;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 京东云对象存储(OSS)存储实现:通过 S3 兼容 API(aws-java-sdk-s3)访问。
|
|
|
+ * <p>对齐 cfc(E:\cfc)的 JdCloudStorageService:
|
|
|
+ * 同样的 endpoint/access-key/secret-key/region 配置与 path-style 访问方式,
|
|
|
+ * 公网 URL 形如 https://{bucket}.{endpoint}/{key}。
|
|
|
+ * <p>与 cfc 共用 bucket 时,通过 {@code jdcloud.key-prefix}(默认 train/)做业务隔离。
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Service
|
|
|
+@ConditionalOnProperty(name = "storage.type", havingValue = "jdcloud")
|
|
|
+public class JdCloudStorageService implements StorageService {
|
|
|
+
|
|
|
+ @Value("${jdcloud.endpoint}")
|
|
|
+ private String endpoint;
|
|
|
+
|
|
|
+ @Value("${jdcloud.access-key}")
|
|
|
+ private String accessKey;
|
|
|
+
|
|
|
+ @Value("${jdcloud.secret-key}")
|
|
|
+ private String secretKey;
|
|
|
+
|
|
|
+ @Value("${jdcloud.bucket}")
|
|
|
+ private String bucket;
|
|
|
+
|
|
|
+ @Value("${jdcloud.region:cn-north-1}")
|
|
|
+ private String region;
|
|
|
+
|
|
|
+ /** 业务前缀:与 cfc 共用 bucket 时避免 key 冲突 */
|
|
|
+ @Value("${jdcloud.key-prefix:train/}")
|
|
|
+ private String keyPrefix;
|
|
|
+
|
|
|
+ private AmazonS3 s3Client;
|
|
|
+
|
|
|
+ @PostConstruct
|
|
|
+ public void init() {
|
|
|
+ BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
|
|
|
+ this.s3Client = AmazonS3ClientBuilder.standard()
|
|
|
+ .withCredentials(new AWSStaticCredentialsProvider(credentials))
|
|
|
+ .withEndpointConfiguration(new AmazonS3ClientBuilder.EndpointConfiguration(endpoint, region))
|
|
|
+ .withPathStyleAccessEnabled(true)
|
|
|
+ .build();
|
|
|
+ log.info("JdCloudStorageService init: endpoint={}, bucket={}, region={}, keyPrefix={}",
|
|
|
+ endpoint, bucket, region, keyPrefix);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public String storeFile(MultipartFile file, String category) {
|
|
|
+ try {
|
|
|
+ return storeBytes(file.getBytes(), category, file.getOriginalFilename(), file.getContentType());
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new RuntimeException("京东云文件读取失败", e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public String storeBytes(byte[] data, String category, String filename, String contentType) {
|
|
|
+ if (data == null || data.length == 0) {
|
|
|
+ throw new RuntimeException("京东云文件存储失败:内容为空");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ String key = buildKey(category, filename);
|
|
|
+ ObjectMetadata metadata = new ObjectMetadata();
|
|
|
+ metadata.setContentLength(data.length);
|
|
|
+ metadata.setContentType(contentType != null ? contentType : "application/octet-stream");
|
|
|
+ s3Client.putObject(new PutObjectRequest(bucket, key,
|
|
|
+ new ByteArrayInputStream(data), metadata));
|
|
|
+ String url = buildPublicUrl(key);
|
|
|
+ log.info("京东云上传成功: key={}, size={}, url={}", key, data.length, url);
|
|
|
+ return url;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("京东云文件存储失败 category={} filename={}", category, filename, e);
|
|
|
+ throw new RuntimeException("京东云文件存储失败", e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void deleteFile(String fileUrl) {
|
|
|
+ if (fileUrl == null || fileUrl.isEmpty()) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ String key = extractKey(fileUrl);
|
|
|
+ if (!key.isEmpty()) {
|
|
|
+ s3Client.deleteObject(bucket, key);
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("删除京东云文件失败: {}", fileUrl, e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private String buildKey(String category, String filename) {
|
|
|
+ String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
|
|
+ String name = UUID.randomUUID().toString() + extensionOf(filename);
|
|
|
+ return normalizePrefix() + "uploads/" + sanitizeCategory(category) + "/" + date + "/" + name;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String normalizePrefix() {
|
|
|
+ String prefix = keyPrefix == null ? "" : keyPrefix.trim();
|
|
|
+ if (prefix.startsWith("/")) {
|
|
|
+ prefix = prefix.substring(1);
|
|
|
+ }
|
|
|
+ if (!prefix.isEmpty() && !prefix.endsWith("/")) {
|
|
|
+ prefix += "/";
|
|
|
+ }
|
|
|
+ return prefix;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String sanitizeCategory(String category) {
|
|
|
+ if (category != null && category.matches("^[A-Za-z0-9_-]{1,32}$")) {
|
|
|
+ return category;
|
|
|
+ }
|
|
|
+ return "general";
|
|
|
+ }
|
|
|
+
|
|
|
+ private String extensionOf(String filename) {
|
|
|
+ if (filename != null && filename.contains(".")) {
|
|
|
+ String ext = filename.substring(filename.lastIndexOf("."));
|
|
|
+ if (ext.matches("^\\.[A-Za-z0-9]{1,10}$")) {
|
|
|
+ return ext;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+
|
|
|
+ private String buildPublicUrl(String key) {
|
|
|
+ String host = endpoint.replaceFirst("^https?://", "");
|
|
|
+ return "https://" + bucket + "." + host + "/" + key;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String extractKey(String fileUrl) {
|
|
|
+ try {
|
|
|
+ URI uri = URI.create(fileUrl);
|
|
|
+ if (uri.getScheme() != null) {
|
|
|
+ String path = uri.getPath();
|
|
|
+ if (path != null) {
|
|
|
+ return path.startsWith("/") ? path.substring(1) : path;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception ignored) {
|
|
|
+ // 非标准 URL:按相对路径处理
|
|
|
+ }
|
|
|
+ return fileUrl.startsWith("/") ? fileUrl.substring(1) : fileUrl;
|
|
|
+ }
|
|
|
+}
|