peter
2025-07-16 076a457c7c7d005075aa8247ee0b214e94418786
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package com.yami.trading.service.impl;
 
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.yami.trading.common.exception.BusinessException;
import com.yami.trading.common.exception.YamiShopBindException;
import com.yami.trading.common.util.PropertiesUtil;
import com.yami.trading.service.AwsS3OSSFileService;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
 
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.*;
 
@Service
@Slf4j
public class AwsS3OSSFileServiceImpl implements AwsS3OSSFileService {
 
    @Value("${oss.aws.s3.bucketName}")
    private String bucketName;
    @Value("${http.prefix}")
    private String httpPrefix;
    //
//    @Value("${images.dir}")
//    private String tempFilePath;
    public static String policyText = "{ \n" +
            "  \"Version\": \"2012-10-17\",\n" +
            "  \"Statement\": [\n" +
            "    {\n" +
            "      \"Effect\": \"Allow\",\n" +
            "      \"Action\": \"s3:*\",\n" +
            "      \"Principal\": \"*\",\n" +
            "      \"Resource\": [\n" +
            "        \"arn:aws:s3:::%s/*\"\n" +
            "      ]\n" +
            "    }\n" +
            "  ]\n" +
            "}";
 
    /**
     * 获取操作客户端
     *
     * @return
     */
    private S3Client getS3Client() {
        AwsCredentials awsCredentials = new AwsCredentials() {
            @Override
            public String accessKeyId() {
                return "AKIARM6B3X65CX7HTKUL";
            }
 
            @Override
            public String secretAccessKey() {
                return "P/icWwYNmUKCPzK11mn7HPoOx+Y4y78G/paUsfCg";
            }
        };
        Region region = Region.US_WEST_1;
        S3Client s3 = S3Client.builder()
                .region(region)
                .credentialsProvider(StaticCredentialsProvider.create(awsCredentials))
                .build();
        return s3;
    }
 
    /**
     * 创建存储桶
     *
     * @param bucketName
     */
    public void createBucket(String bucketName) {
        log.debug("AwsS3OSSFileService createBucket bucketName:{}", bucketName);
        try {
            S3Client s3Client = getS3Client();
            S3Waiter s3Waiter = s3Client.waiter();
            CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
            s3Client.createBucket(bucketRequest);
            HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
            WaiterResponse<HeadBucketResponse> r = s3Waiter.waitUntilBucketExists(bucketRequestWait);
            log.info("AwsS3OSSFileService createBucket result :{}", JSONObject.toJSONString(r));
        } catch (S3Exception e) {
            log.error("AwsS3OSSFileService createBucket Exception", e.getMessage(), e.awsErrorDetails().errorMessage(), e);
        }
    }
 
    /**
     * 设置存储桶策略
     *
     * @param bucketName
     */
    public void setPolicy(String bucketName) {
        log.info("AwsS3OSSFileService setPolicy bucketName:{},policyText:{}", bucketName, policyText);
        try {
            S3Client s3Client = getS3Client();
            PutBucketPolicyRequest policyReq = PutBucketPolicyRequest.builder()
                    .bucket(bucketName)
                    .policy(String.format(policyText, bucketName))
                    .build();
            PutBucketPolicyResponse r = s3Client.putBucketPolicy(policyReq);
            log.info("AwsS3OSSFileService setPolicy result :{}", r.toString());
            log.info("AwsS3OSSFileService setPolicy result :{}", JSONObject.toJSONString(r));
        } catch (S3Exception e) {
            log.error("AwsS3OSSFileService setPolicy Exception", e.getMessage(), e.awsErrorDetails().errorMessage(), e);
        }
    }
 
    /**
     * 获取文件访问链接
     *
     * @param keyName
     */
    @Override
    public String getUrl(String keyName) {
        if (StrUtil.isEmpty(keyName)) {
            return null;
        }
        return httpPrefix + keyName;
 
    }
 
    /**
     * 上传本地文件
     *
     * @return
     */
    @Override
    public String uploadFile(String moduleName, MultipartFile file) {
        // 兼容c端组件上传原理
        String fileType = file.getOriginalFilename();
        if (StrUtil.isEmpty(fileType) || fileType.contains("blob")) {
            fileType = "blob.png";
        }
 
        // 生成唯一的文件名
        String id = UUID.randomUUID().toString();
        String path = LocalDate.now() + "/" + id + fileType;
 
        // 确保目标文件夹存在
        File targetDir = new File(PropertiesUtil.getProperty("loca.images.dir")  + "/" + LocalDate.now());
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
 
        // 构建本地文件路径
        File localFile = new File(targetDir, id + fileType);
 
        // 打印上传路径
        log.info("LocalFileUploadService uploadFile localFilePath: {}", localFile.getAbsolutePath());
 
        try {
            // 将文件保存到本地
            file.transferTo(localFile);
 
            // 如果需要自定义元数据,可以在此处理
            Map<String, String> metadata = new HashMap<>();
            metadata.put("x-amz-meta-myVal", "test");  // 如果需要元数据,可以放在文件名或其他地方
 
            // 返回相对路径
            return path;
 
        } catch (IOException e) {
            log.error("LocalFileUploadService uploadFile IOException", e.getMessage(), e);
            throw new YamiShopBindException("文件上传失败");
        }
    }
//    /**
//     * 上传本地文件
//     *
//     * @return
//     */
//    public String putS3Object(String moduleName, MultipartFile file, Float quality) {
//        String fileType = FilenameUtils.getExtension(file.getOriginalFilename());
//        String id = UUID.randomUUID().toString();
//        String path = moduleName + "/" + LocalDate.now() + "/" + id + "." + fileType;
//        String thumbnailPath = moduleName + "/" + LocalDate.now() + "/" + id + "_thumbnail." + fileType;
//
//        log.info("AwsS3OSSFileService putS3Object bucketName:{},objectKey:{},objectPath:{}", bucketName, path, file.getName());
//        try {
//            ByteArrayOutputStream bs = cloneInputStream(file.getInputStream());
//
//            InputStream orgIS = new ByteArrayInputStream(bs.toByteArray());
//
//            Map<String, String> metadata = new HashMap<>();
//            metadata.put("x-amz-meta-myVal", "test");
//            PutObjectRequest putOb = PutObjectRequest.builder()
//                    .bucket(bucketName)
//                    .key(path)
//                    .metadata(metadata)
//                    .build();
//            S3Client s3Client = getS3Client();
//            s3Client.putObject(putOb, RequestBody.fromInputStream(orgIS, file.getSize()));
//
//            InputStream thumbnailIS = new ByteArrayInputStream(bs.toByteArray());
//
//            File tempFile = new File(tempFilePath + "/temp-img/");
//            if (!tempFile.exists()) {
//                tempFile.mkdirs();
//            }
//            Thumbnails.of(thumbnailIS).scale(1D).outputQuality(quality).toFile(tempFilePath + "/temp-img/" + id + "_thumbnail." + fileType);
//
//            PutObjectRequest putThumbnailOb = PutObjectRequest.builder()
//                    .bucket(bucketName)
//                    .key(thumbnailPath)
//                    .metadata(metadata)
//                    .build();
//            File thumbnailFile = new File(tempFilePath + "/temp-img/" + id + "_thumbnail." + fileType);
//            s3Client.putObject(putThumbnailOb, RequestBody.fromInputStream(Files.newInputStream(thumbnailFile.toPath()), thumbnailFile.length()));
//            return path;
//        } catch (S3Exception e) {
//            log.error("AwsS3OSSFileService putS3Object S3Exception", e.getMessage(), e.awsErrorDetails().errorMessage(), e);
//            throw new BusinessException("文件上传失败");
//        } catch (IOException e) {
//            log.error("AwsS3OSSFileService putS3Object IOException", e.getMessage(), e);
//            throw new BusinessException("文件上传失败");
//        }
//    }
 
    private static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            log.error("cloneInputStream IOException", e.getMessage(), e);
        }
        return null;
    }
 
    /**
     * 判断文件是否为图片
     *
     * @param fileName
     * @return
     */
    public boolean isImageFile(String fileName) {
        List<String> imgTypes = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp");
        if (StrUtil.isEmpty(fileName)) {
            return false;
        }
        String fileType = FilenameUtils.getExtension(fileName);
        return imgTypes.contains(fileType.toLowerCase());
    }
}