5 小时以前 9bad721754fe8bbe2e5f459d0706e0fefac569f3
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
package cn.iocoder.yudao.module.system.service.storage;
 
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.storage.vo.SystemStorageBlobRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.storage.SystemStorageBlobDO;
import cn.iocoder.yudao.module.system.dal.mysql.storage.SystemStorageBlobMapper;
import cn.iocoder.yudao.module.system.framework.storage.config.StorageProperties;
import cn.iocoder.yudao.module.system.util.storage.StorageFileUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.crypto.SecretKey;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
 
/**
 * 文件主表 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@RequiredArgsConstructor
public class SystemStorageBlobServiceImpl implements SystemStorageBlobService {
 
    private final StorageProperties properties;
    @Resource
    private SystemStorageBlobMapper storageBlobMapper;
    private final StorageFileUtil fileUtil;
 
    @Override
    public List<SystemStorageBlobRespVO> upload(List<MultipartFile> files, Boolean isPublic) {
        if (files == null || files.isEmpty()) {
            throw exception(STORAGE_FILE_EMPTY);
        }
 
        List<SystemStorageBlobRespVO> result = new ArrayList<>();
 
        for (MultipartFile file : files) {
            if (file == null || file.isEmpty()) {
                throw exception(STORAGE_FILE_EMPTY);
            }
 
            String originalFileName = StringUtils.hasText(file.getOriginalFilename())
                    ? StringUtils.cleanPath(file.getOriginalFilename())
                    : UUID.randomUUID().toString();
            String fileName = UUID.randomUUID() + "_" + originalFileName;
            String relativePath = fileUtil.buildRelativePath();
            File targetDirectory = new File(properties.getPath(), relativePath);
            if (!targetDirectory.exists() && !targetDirectory.mkdirs()) {
                throw exception(STORAGE_BLOB_UPLOAD_FAILED);
            }
            File dest = new File(targetDirectory, fileName);
 
            SystemStorageBlobRespVO blobRespVO;
            try {
                file.transferTo(dest);
                blobRespVO = createStorageBlob(file, originalFileName, fileName, relativePath, isPublic);
                if (blobRespVO == null || blobRespVO.getId() == null) {
                    throw exception(STORAGE_BLOB_UPLOAD_FAILED);
                }
            } catch (RuntimeException e) {
                if (dest.exists()) {
                    dest.delete();
                }
                throw e;
            } catch (IOException e) {
                throw exception(STORAGE_BLOB_UPLOAD_FAILED);
            }
 
            result.add(blobRespVO);
        }
        return result;
    }
 
    @Override
    public SystemStorageBlobRespVO saveBlob(byte[] content, String originalFileName, String contentType, Boolean isPublic) {
        if (content == null || content.length == 0) {
            throw exception(STORAGE_FILE_EMPTY);
        }
        // 文件名来自调用方,仍要 cleanPath:它会拼进落盘文件名,不能带出目录层级
        String safeName = StringUtils.hasText(originalFileName)
                ? StringUtils.cleanPath(originalFileName)
                : UUID.randomUUID().toString();
        String fileName = UUID.randomUUID() + "_" + safeName;
        String relativePath = fileUtil.buildRelativePath();
        File targetDirectory = new File(properties.getPath(), relativePath);
        if (!targetDirectory.exists() && !targetDirectory.mkdirs()) {
            throw exception(STORAGE_BLOB_UPLOAD_FAILED);
        }
        File dest = new File(targetDirectory, fileName);
        try {
            Files.write(dest.toPath(), content);
            SystemStorageBlobRespVO blobRespVO = persistBlob(contentType, safeName, fileName,
                    relativePath, content.length, isPublic);
            if (blobRespVO == null || blobRespVO.getId() == null) {
                throw exception(STORAGE_BLOB_UPLOAD_FAILED);
            }
            return blobRespVO;
        } catch (RuntimeException e) {
            if (dest.exists()) {
                dest.delete();
            }
            throw e;
        } catch (IOException e) {
            if (dest.exists()) {
                dest.delete();
            }
            throw exception(STORAGE_BLOB_UPLOAD_FAILED);
        }
    }
 
    @Override
    public File getFileByToken(String fileName, String token) {
        if (!StringUtils.hasText(token)) {
            throw exception(STORAGE_BLOB_TOKEN_INVALID);
        }
 
        String secretStr = properties.getJwtSecret();
        SecretKey key = Keys.hmacShaKeyFor(secretStr.getBytes(StandardCharsets.UTF_8));
        Claims claims;
        try {
            claims = Jwts.parser()
                    .verifyWith(key)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (Exception e) {
            throw exception(STORAGE_BLOB_TOKEN_INVALID);
        }
        if (!fileName.equals(claims.getSubject())) {
            throw exception(STORAGE_BLOB_TOKEN_MISMATCH);
        }
        fileUtil.validateTokenUsage(token);
 
        SystemStorageBlobDO blob = storageBlobMapper.selectByUidFilename(fileName);
        String path = blob == null ? claims.get("path", String.class) : blob.getPath();
        if (!StringUtils.hasText(path)) {
            return new File(properties.getPath(), fileName);
        }
        return new File(new File(properties.getPath(), path), fileName);
    }
 
    @Override
    public File getPublicFile(String fileName, String publicKey) {
        if (!StringUtils.hasText(fileName)) {
            throw exception(STORAGE_BLOB_NOT_EXISTS);
        }
        if (!StringUtils.hasText(publicKey)) {
            throw exception(STORAGE_BLOB_PUBLIC_KEY_INVALID);
        }
        SystemStorageBlobDO blob = storageBlobMapper.selectByUidFilenameAndResourceKey(fileName, publicKey);
        if (blob == null) {
            throw exception(STORAGE_BLOB_PUBLIC_KEY_INVALID);
        }
        String path = blob.getPath();
        if (!StringUtils.hasText(path)) {
            return new File(properties.getPath(), fileName);
        }
        return new File(new File(properties.getPath(), path), fileName);
    }
 
    @Override
    public String getDownloadFileName(String fileName) {
        SystemStorageBlobDO blob = storageBlobMapper.selectByUidFilename(fileName);
        if (blob == null || !StringUtils.hasText(blob.getOriginalFilename())) {
            return fileName;
        }
        return blob.getOriginalFilename();
    }
 
    @Override
    public SystemStorageBlobDO getStorageBlob(Long id) {
        return storageBlobMapper.selectById(id);
    }
 
    @Override
    public void deleteStorageBlobs(List<Long> ids) {
        fileUtil.deleteStorageBlobs(ids);
    }
 
    private SystemStorageBlobRespVO createStorageBlob(MultipartFile file, String originalFileName,
                                                      String fileName, String relativePath, Boolean isPublic) {
        return persistBlob(file.getContentType(), originalFileName, fileName,
                relativePath, file.getSize(), isPublic);
    }
 
    /**
     * 落库 + 拼预览/下载地址。
     * <p>
     * 两条上传路径({@link #upload} 的 MultipartFile、{@link #saveBlob} 的 byte[])共用这一步,
     * 只在这里维护签名 URL 的拼法,避免两处各写一遍后地址格式走偏。
     */
    private SystemStorageBlobRespVO persistBlob(String contentType, String originalFileName, String fileName,
                                                String relativePath, long byteSize, Boolean isPublic) {
        SystemStorageBlobDO blob = new SystemStorageBlobDO();
        blob.setResourceKey(UUID.randomUUID().toString().replace("-", ""));
        blob.setContentType(contentType);
        blob.setOriginalFilename(originalFileName);
        blob.setUidFilename(fileName);
        blob.setByteSize(byteSize);
        blob.setPath(relativePath);
        storageBlobMapper.insert(blob);
 
        // 构建返回 VO
        SystemStorageBlobRespVO respVO = BeanUtils.toBean(blob, SystemStorageBlobRespVO.class);
        if (Boolean.TRUE.equals(isPublic)) {
            respVO.setPreviewURL(fileUtil.buildSignedUrl(blob, "/preview/", BigDecimal.valueOf(-1)));
            respVO.setDownloadURL(fileUtil.buildSignedUrl(blob, "/download/", BigDecimal.valueOf(-1)));
        } else {
            respVO.setPreviewURL(fileUtil.buildSignedPreviewUrl(blob));
            respVO.setUrl(fileUtil.buildSignedPreviewUrl(blob));
            respVO.setName(blob.getOriginalFilename());
            respVO.setDownloadURL(fileUtil.buildSignedDownloadUrl(blob));
        }
        return respVO;
    }
 
}