lxp
2025-03-13 b7c4edd36912d26aa2e8e6fa5605c370bb2e478a
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
package com.ruoyi.common.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.MinioConfig;
import com.ruoyi.common.enums.AttachmentType;
import com.ruoyi.common.mapper.AttachmentTableMapper;
import com.ruoyi.common.pojo.AttachmentTable;
import com.ruoyi.common.service.AttachmentTableService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import io.minio.*;
import io.minio.http.Method;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
 
@Service
@AllArgsConstructor
public class AttachmentTableServiceImpl  extends ServiceImpl<AttachmentTableMapper, AttachmentTable> implements AttachmentTableService {
 
    private MinioConfig minioConfig;
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(MultipartFile file, Integer type, Integer id) {
        MinioClient build = MinioClient.builder()
                .endpoint(minioConfig.getEndpoint(), minioConfig.getPort(), minioConfig.getSecure())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        try(InputStream inputStream = file.getInputStream()) {
            build.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType("application/octet-stream")
                            .userMetadata(Collections.singletonMap("Content-Disposition", "attachment; filename=\"" + fileName + "\""))
                            .build()
            );
            // 保存到数据库
            AttachmentTable attachmentTable = new AttachmentTable();
            attachmentTable.setSubclassId(id);
            attachmentTable.setFileName(fileName);
            attachmentTable.setOriginalFileName(file.getOriginalFilename());
            attachmentTable.setFileType(file.getContentType());
            attachmentTable.setBucketName(minioConfig.getBucketName());
            attachmentTable.setOtherTableName(AttachmentType.getAttachmentValue(type));
            baseMapper.insert(attachmentTable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void downLoad(Integer id, Integer type,String code,String suffix, HttpServletResponse response)   {
        // 查询数据库
        List<AttachmentTable> list = baseMapper.selectList(new LambdaQueryWrapper<AttachmentTable>()
                .eq(AttachmentTable::getSubclassId, id)
                .eq(AttachmentTable::getOtherTableName, AttachmentType.getAttachmentValue(type))
                .like(AttachmentTable::getFileName, suffix)
                .orderByDesc(AttachmentTable::getId));
        if(CollectionUtils.isNotEmpty(list)) {
            AttachmentTable attachmentTable = list.get(0);
            String fileName = attachmentTable.getFileName(); // 文件名
            MinioClient build = MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint(), minioConfig.getPort(), minioConfig.getSecure())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            try( InputStream inputStream = build.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
                 ServletOutputStream stream = response.getOutputStream()) {
                String finalName = "";
                String fileNameMinIo = attachmentTable.getFileName();
                String suffix1 = fileNameMinIo.substring(fileNameMinIo.lastIndexOf(".")+1);
                String contentType = getContentType(suffix1);
                if(StringUtils.isNotEmpty(code)) {
                    finalName = code + "." + suffix1;
                }else {
                    finalName = fileNameMinIo;
                }
                // 设置响应头
                response.setContentType(contentType);
                response.setHeader("Content-disposition", "attachment;filename=" + finalName);
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) != -1) {
                    stream.write(bytes, 0, len);
                    stream.flush();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
 
 
        }
    }
 
    @Override
    public Map<String, Object> getAttachmentList(Integer id, Integer type,String suffix) {
        HashMap<String, Object> map = new HashMap<>();
        // 查询数据库
        List<AttachmentTable> list = baseMapper.selectList(new LambdaQueryWrapper<AttachmentTable>()
                .eq(AttachmentTable::getSubclassId, id)
                .eq(AttachmentTable::getOtherTableName, AttachmentType.getAttachmentValue(type))
                .like(StringUtils.isNotEmpty(suffix),AttachmentTable::getFileName, suffix)
                .orderByDesc(AttachmentTable::getId));
        if(CollectionUtils.isNotEmpty(list)) {
            String contentType = getContentType(suffix.replace(".",""));
            map.put("contentType", contentType);
            map.put("suffix", suffix);
        }
        return map;
    }
 
    @Override
    public String getURL(Integer id, Integer type , String suffix) {
        String url = "";
        // 查询数据库 获取最新文件名
        List<AttachmentTable> attachmentTables = baseMapper.selectList(new LambdaQueryWrapper<AttachmentTable>()
                .eq(AttachmentTable::getSubclassId, id)
                .eq(AttachmentTable::getOtherTableName, AttachmentType.getAttachmentValue(type))
                .like(AttachmentTable::getFileName, suffix)
                .orderByDesc(AttachmentTable::getId));
        if(CollectionUtils.isNotEmpty(attachmentTables)) {
            AttachmentTable attachmentTable = attachmentTables.get(0);
            MinioClient build = MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint(), minioConfig.getPort(), minioConfig.getSecure())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            try {
                 url = build.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(minioConfig.getBucketName())
                        .object(attachmentTable.getFileName())
                        .expiry(60 * 60 * 24)
                        .build());
 
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
 
        }
        return url;
    }
 
    public InputStream  getInputStream(Integer id, Integer type , String suffix) {
        InputStream inputStream = null;
        // 查询数据库 获取最新文件名
        List<AttachmentTable> attachmentTables = baseMapper.selectList(new LambdaQueryWrapper<AttachmentTable>()
                .eq(AttachmentTable::getSubclassId, id)
                .eq(AttachmentTable::getOtherTableName, AttachmentType.getAttachmentValue(type))
                .like(StringUtils.isNotEmpty(suffix),AttachmentTable::getFileName, suffix)
                .orderByDesc(AttachmentTable::getId));
        if(CollectionUtils.isNotEmpty(attachmentTables)) {
            AttachmentTable attachmentTable = attachmentTables.get(0);
            MinioClient build = MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint(), minioConfig.getPort(), minioConfig.getSecure())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            try {
                inputStream  = build.getObject(
                        GetObjectArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .object(attachmentTable.getFileName())
                                .build());
 
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return inputStream;
    }
 
 
 
 
    // 根据文件扩展名获取 MIME 类型
    private String getContentType(String fileExtension) {
        switch (fileExtension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "pdf":
                return "application/pdf";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case "ppt":
            case "pptx":
                return "application/vnd.ms-powerpoint";
            default:
                return "application/octet-stream"; // 默认二进制流
        }
    }
}