liusuyi
2025-12-23 c7fa563f9a951c647725c3d0e02b7bce366d23ea
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
package com.ard.oss.service.impl;
 
import com.ard.common.config.OssConfiguration;
import com.ard.common.exception.file.FileNameLengthLimitExceededException;
import com.ard.common.exception.file.FileSizeLimitExceededException;
import com.ard.common.exception.file.InvalidExtensionException;
import com.ard.common.utils.file.FileUploadUtils;
import com.ard.common.utils.file.MimeTypeUtils;
import com.ard.oss.model.CredentialsDTO;
import com.ard.oss.model.enums.OssTypeEnum;
import com.ard.oss.service.IOssService;
import io.minio.PutObjectArgs;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
 
import static com.ard.common.utils.file.FileUploadUtils.assertAllowed;
import static com.ard.common.utils.file.FileUploadUtils.extractFilename;
 
/**
 * @author sean
 * @version 1.0
 * @date 2022/5/30
 */
@Service
public class OssServiceContext {
 
    private IOssService ossService;
 
    @Autowired
    public OssServiceContext(List<IOssService> ossServices, OssConfiguration configuration) {
        if (!OssConfiguration.enable) {
            return;
        }
        this.ossService = ossServices.stream()
                .filter(ossService -> ossService.getOssType().equals(OssConfiguration.provider))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Oss provider is illegal. Optional: " +
                        Arrays.toString(Arrays.stream(OssTypeEnum.values()).map(OssTypeEnum::getType).toArray())));
    }
 
    IOssService getOssService() {
        return this.ossService;
    }
 
    public CredentialsDTO getCredentials() {
        return this.ossService.getCredentials();
    }
 
    public URL getObjectUrl(String bucket, String objectKey) {
        if (!StringUtils.hasText(bucket) || !StringUtils.hasText(objectKey)) {
            throw new IllegalArgumentException();
        }
        return this.ossService.getObjectUrl(bucket, objectKey);
    }
 
    public Boolean deleteObject(String bucket, String objectKey) {
        return this.ossService.deleteObject(bucket, objectKey);
    }
 
    public InputStream getObject(String bucket, String objectKey) {
        return this.ossService.getObject(bucket, objectKey);
    }
 
    public void putObject(String bucket, String objectKey, InputStream stream) {
        this.ossService.putObject(bucket, objectKey, stream);
    }
 
 
    void createClient() {
        this.ossService.createClient();
    }
 
    /**
     * 以默认BucketName配置上传到Minio服务器
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public String upload(MultipartFile file) throws IOException {
        try {
            return upload(OssConfiguration.bucket, file);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }
 
    /**
     * 自定义bucketName配置上传到Minio服务器
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public String upload(String bucket, MultipartFile file) throws IOException {
        try {
            return upload(bucket, null, file);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }
 
    /**
     * ✅ 通用上传方法:
     * - bucket 必传
     * - object 可选(为空则自动生成)
     * - 返回永久访问 URL
     */
    public String upload(String bucket, String object, MultipartFile file) throws IOException {
        try {
            // 校验文件名长度
            int fileNameLength = file.getOriginalFilename().length();
            if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
                throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            }
 
            // 检查文件扩展名是否合法
            assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
 
            // ✅ 如果 object 为空,则自动生成文件名
            String objectName = (object == null || object.isEmpty())
                    ? extractFilename(file)
                    : object;
 
            // 通过文件扩展名获取 MIME 类型
            String contentType = getMimeTypeByExtension(file.getOriginalFilename());
 
            @Cleanup
            InputStream inputStream = file.getInputStream();
            // 上传文件到 Minio
            this.ossService.putObject(bucket, objectName, inputStream, contentType);
 
            return buildUrl(bucket, objectName);
        } catch (Exception e) {
            throw new IOException("Upload failed: " + e.getMessage(), e);
        }
    }
 
    public String upload(String bucket, String objectKey, InputStream input) {
        try {
            // 上传文件
            this.ossService.putObject(bucket, objectKey, input);
            return buildUrl(bucket, objectKey);
        } catch (Exception e) {
            throw new RuntimeException("Upload failed: " + e.getMessage(), e);
        }
    }
 
    public String upload(String bucket, String objectKey, InputStream input, String contentType) {
        try {
            // 上传文件时指定 Content-Type
            this.ossService.putObject(bucket, objectKey, input, contentType);
            return buildUrl(bucket, objectKey);
        } catch (Exception e) {
            throw new RuntimeException("Upload failed: " + e.getMessage(), e);
        }
    }
    // 获取文件 MIME 类型
    public String getMimeTypeByExtension(String fileName) {
        // 获取文件扩展名
        String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
 
        // 根据文件扩展名返回 MIME 类型
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "pdf":
                return "application/pdf";
            case "txt":
                return "text/plain";
            case "html":
                return "text/html";
            case "json":
                return "application/json";
            case "csv":
                return "text/csv";
            case "zip":
                return "application/zip";
            // 添加更多的扩展名映射
            default:
                return "application/octet-stream";  // 默认 MIME 类型
        }
    }
 
    // 构建url
    private String buildUrl(String bucket, String key) {
        String base = OssConfiguration.endpoint;
        if (!base.endsWith("/")) {
            base += "/";
        }
        return base + bucket + "/" + key;
    }
 
}