xiangpei
2025-05-14 47cd9ecc0eff38ffe6b3b794b2bf197e958f4403
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
package com.mindskip.xzs.utility.minio;
 
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
 
 
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
 
@Component
public class AwsMinIoUtil {
 
 
    private static String endpoint;
 
    private static final Logger logger = LoggerFactory.getLogger(AwsMinIoUtil.class);
 
    private AmazonS3 s3client;
 
    private static String accessKey;
 
    private static String secretKey;
 
    private static String bucket;
 
 
    @Value("${aws.endpoint}")
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
 
    @Value("${aws.accessKey}")
    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }
 
    @Value("${aws.secretKey}")
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
 
    @Value("${aws.bucket}")
    public void setBucket(String bucket) {
        this.bucket = bucket;
    }
 
    public static String getEndpoint() {
        return endpoint;
    }
 
    public static String getAccessKey() {
        return accessKey;
    }
 
    public static String getSecretKey() {
        return secretKey;
    }
 
    public static String getBucket() {
        return bucket;
    }
 
    public void init() throws MalformedURLException {
        URL endpointUrl = new URL(endpoint);
        String protocol = endpointUrl.getProtocol();
        int port = endpointUrl.getPort() == -1 ? endpointUrl.getDefaultPort() : endpointUrl.getPort();
 
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setSignerOverride("S3SignerType");
        clientConfig.setProtocol(Protocol.valueOf(protocol.toUpperCase()));
 
        // 禁用证书检查,避免https自签证书校验失败
        System.setProperty("com.amazonaws.sdk.disableCertChecking", "true");
        // 屏蔽 AWS 的 MD5 校验,避免校验导致的下载抛出异常问题
        System.setProperty("com.amazonaws.services.s3.disableGetObjectMD5Validation", "true");
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        // 创建 S3Client 实例
        AmazonS3 s3client = new AmazonS3Client(awsCredentials, clientConfig);
        s3client.setEndpoint(endpointUrl.getHost() + ":" + port);
        s3client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
        this.s3client = s3client;
    }
 
    /**
     * 创建桶
     * @param bucket
     * @return
     */
    public boolean createBucket(String bucket)  {
        try {
            s3client.createBucket(bucket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
 
    /**
     * 删除桶
     * @param bucket
     * @return
     */
    public boolean deleteBucket(String bucket)  {
        try {
            s3client.deleteBucket(bucket);
            logger.info("删除bucket[{}]成功", bucket);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    /**
     * 判断桶是否存在
     * @param bucket
     * @return
     */
    public boolean bucketExists(String bucket)  {
        try {
            return s3client.doesBucketExist(bucket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 
    /**
     * 上传对象
     * @param input
     */
    public String upload( InputStream input, MultipartFile multipartFile)  {
        try {
            init();
            // 创建文件上传的元数据
            ObjectMetadata meta = new ObjectMetadata();
            // 设置文件上传长度
            meta.setContentLength(input.available());
            // 上传
            String path = extractFilename(multipartFile);
            s3client.putObject(bucket, path, input, meta);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     * 下载对象
     * @param bucket
     * @param objectId
     * @return
     */
    public InputStream download(String bucket, String objectId)  {
        try {
            S3Object o = s3client.getObject(bucket, objectId);
            return o.getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
//    public void download(String bucket, String objectId, OutputStream out)  {
//        S3Object o = s3client.getObject(bucket, objectId);
//        try (InputStream in = o.getObjectContent()) {
//            IOUtils.copyLarge(in, out);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
 
    /**
     * 判断对象是否存在
     * @param bucket
     * @param objectId
     * @return
     */
    public boolean existObject(String bucket, String objectId)  {
        try {
            return s3client.doesObjectExist(bucket, objectId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 删除对象
     * @param bucket
     * @param objectId
     * @return
     */
    public boolean deleteObject(String bucket, String objectId)  {
        try {
            s3client.deleteObject(bucket, objectId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    public void close()  {
        s3client = null;
    }
 
    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
    }
 
    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }
 
 
 
}