maven
20 小时以前 ca77a052f3af47697cd3cf0a4f71468feb8455af
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
package com.ruoyi.basic.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.entity.StorageAttachment;
import com.ruoyi.basic.entity.StorageBlob;
import com.ruoyi.basic.entity.dto.StorageBlobDTO;
import com.ruoyi.basic.mapper.StorageAttachmentMapper;
import com.ruoyi.basic.mapper.StorageBlobMapper;
import com.ruoyi.basic.service.StorageBlobService;
import com.ruoyi.common.core.domain.MinioResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.MinioUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.util.TempFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 通用文件上传的附件信息 服务实现类
 * </p>
 *
 * @author ruoyi
 * @since 2025-05-29
 */
@Service
@RequiredArgsConstructor
public class StorageBlobServiceImpl extends ServiceImpl<StorageBlobMapper, StorageBlob> implements StorageBlobService {
    @Autowired
    private StorageAttachmentMapper storageAttachmentMapper;
 
    @Autowired
    private StorageBlobMapper storageBlobMapper;
 
    @Autowired
    private MinioUtils minioUtils;
 
    @Value("${file.file-url}")
    private String fileUrl;
 
    @Override
    public List<StorageBlobDTO> uploads(List<MultipartFile> files, String bucketName, Long type) {
        // 若没传入bucketName,则使用默认bucketName
        if (StringUtils.isEmpty(bucketName)) {
            bucketName = minioUtils.getDefaultBucket();
        }
        List<StorageBlobDTO> storageBlobDTOs = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                validateFileExtension(file);
//                MinioResult res = minioUtils.upload(bucketName, file, false);
                // 不使用minio,使用本地文件上传
                String res = uploadFile(file, type);
                StorageBlobDTO dto = buildStorageBlobDTO(file, res, bucketName, type);
                dto.setFileUrl(res);
                storageBlobMapper.insert(dto);
                storageBlobDTOs.add(dto);
 
            } catch (InvalidExtensionException e) {
                throw new RuntimeException("不支持的文件类型:" + file.getOriginalFilename(), e);
            } catch (Exception e) {
                throw new RuntimeException("上传文件失败:" + file.getOriginalFilename(), e);
            }
        }
        return storageBlobDTOs;
    }
 
    @Override
    public List<StorageBlobDTO> updateStorageBlobs(List<MultipartFile> files, String bucketName,Long type) {
 
        // 若没传入bucketName,则使用默认bucketName
        if (StringUtils.isEmpty(bucketName)) {
            bucketName = minioUtils.getDefaultBucket();
        }
        List<StorageBlobDTO> storageBlobDTOs = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                validateFileExtension(file);
                MinioResult res = minioUtils.upload(bucketName, file, false);
//                String res = uploadFile(file, type);
                StorageBlobDTO dto = buildStorageBlobDTO(file, res, bucketName, type);
 
                storageBlobMapper.insert(dto);
                storageBlobDTOs.add(dto);
 
            } catch (InvalidExtensionException e) {
                throw new RuntimeException("不支持的文件类型:" + file.getOriginalFilename(), e);
            } catch (Exception e) {
                throw new RuntimeException("上传文件失败:" + file.getOriginalFilename(), e);
            }
        }
        return storageBlobDTOs;
    }
 
    @Value("${file.upload-dir}")
    private String tempDir;
 
    public String uploadFile(MultipartFile file, Long type) throws IOException {
        // 1. 生成临时文件ID和路径
        String tempId = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        if(originalFilename == null) throw new IOException("文件名不能为空");
 
        Path tempFilePath = Paths.get(tempDir, tempId + "_" + file.getOriginalFilename()); //windows上传路径
        Path prodFilePath = Paths.get(fileUrl, tempId + "_" + file.getOriginalFilename()); //nginx代理路径
 
        // 2. 确保目录存在
        Path parentDir = tempFilePath.getParent();
        if (parentDir != null) {
            Files.createDirectories(parentDir); // 递归创建目录
        }
 
        // 3. 保存文件到临时目录
        file.transferTo(tempFilePath.toFile());
 
        return prodFilePath.toString();
    }
 
    private void validateFileExtension(MultipartFile file) throws InvalidExtensionException {
        String filename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(filename).toLowerCase();
        List<String> allowedExtensions = Arrays.asList(
                // 图片
                "jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "ico", "svg",
 
                // 文档
                "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "rtf", "md", "csv", "odt",
 
                // 视频
                "mp4", "mov", "avi", "wmv", "flv", "mkv", "webm", "mpeg", "3gp","MOV",
 
                // 音频
                "mp3", "wav", "ogg", "aac", "flac", "m4a", "wma", "amr",
 
                // 压缩包
                "zip", "rar", "7z", "tar", "gz", "bz2", "xz",
 
                // 编程代码文件
                "java", "py", "js", "ts", "html", "css", "cpp", "c", "cs", "json", "xml", "sql", "yaml", "yml", "sh", "bat",
 
                // 安装程序 & 二进制
                "exe", "apk", "dmg", "msi", "bin", "iso",
 
                // 设计类
                "psd", "ai", "xd", "sketch", "fig"
        );
 
        if (!allowedExtensions.contains(extension)) {
            throw new BaseException("文件类型不被允许:" + extension);
        }
    }
 
    private StorageBlobDTO buildStorageBlobDTO(MultipartFile file, MinioResult res, String bucketName, Long type) {
        StorageBlobDTO dto = new StorageBlobDTO();
        dto.setContentType(file.getContentType());
        dto.setBucketFilename(res.getBucketFileName());
        dto.setOriginalFilename(res.getOriginalName());
        dto.setByteSize(file.getSize());
        dto.setKey(IdUtils.simpleUUID());
        dto.setBucketName(bucketName);
        dto.setUrl(minioUtils.getPreviewUrl(res.getBucketFileName(), bucketName, false));
        dto.setDownloadUrl(minioUtils.getDownloadUrl(res.getBucketFileName(), bucketName));
 
        if (type != null) {
            dto.setType(type);
        }
 
        return dto;
    }
 
    private StorageBlobDTO buildStorageBlobDTO(MultipartFile file, String res, String bucketName, Long type) {
        StorageBlobDTO dto = new StorageBlobDTO();
        dto.setContentType(file.getContentType());
        dto.setBucketFilename("sys");
        dto.setOriginalFilename(file.getOriginalFilename());
        dto.setByteSize(file.getSize());
        dto.setKey(IdUtils.simpleUUID());
        dto.setBucketName(bucketName);
        dto.setUrl(res);
        dto.setDownloadUrl(res);
 
        if (type != null) {
            dto.setType(type);
        }
 
        return dto;
    }
 
    @Override
    public int deleteStorageBlobs(StorageAttachment attachment) {
        List<StorageAttachment> attachments = storageAttachmentMapper.selectList(new LambdaQueryWrapper<StorageAttachment>()
                .eq(StorageAttachment::getRecordId, attachment.getRecordId())
                .eq(StorageAttachment::getRecordType, attachment.getRecordType())
                .eq(StorageAttachment::getName, attachment.getName()));
        List<Long> ids = attachments.stream()
                .map(StorageAttachment::getStorageBlobId)
                .collect(Collectors.toList());
        List<StorageBlob> storageBlobs = new ArrayList<>();
        if (!ids.isEmpty()) {
            // 只在ID列表非空时执行查询
            storageBlobs = storageBlobMapper.selectList(
                    new LambdaQueryWrapper<StorageBlob>().in(StorageBlob::getId, ids)
            );
        }
        
        // 移除MinIO中的文件
        if (!storageBlobs.isEmpty()) {
            for (StorageBlob storageBlob : storageBlobs) {
                minioUtils.removeObjectsResult(storageBlob.getBucketName(), storageBlob.getBucketFilename());
            }
        }
 
        // 删除数据库记录
        if (!ids.isEmpty()) {
            return storageBlobMapper.delete(
                    new QueryWrapper<StorageBlob>().lambda().in(StorageBlob::getId, ids)
            );
        }
        return 0;
    }
 
 
}