kongzy
2024-07-05 14821e28286d773ad5ff2c13510e39c5eb117daf
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
package com.gkhy.exam.common.utils;
 
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.gkhy.exam.common.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
@Component
@Slf4j
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;
 
    /**
     * 查看存储bucket是否存在
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found=false;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error("minio校验bucket失败:{}",e.getMessage());
        }
        return found;
    }
 
    /**
     * 文件上传 上传完成后请关闭文件流
     *
     * @param fileName 带后缀的文件名 检验日期yyyyMMdd加16位随机码
     * @param stream   文件流 要上传文件的流
     */
    public String fileUploader( String fileName, InputStream stream) {
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).stream(stream, stream.available(), -1).contentType("application/octet-stream").build();
            // 使用putObject上传一个文件到文件分类
            minioClient.putObject(objectArgs);
        }catch (Exception e) {
            log.error("minio上传文件失败:{}",e.getMessage());
            return null;
        }
        return fileName;
    }
 
 
    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        String fileName = UUID.fastUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            log.error("minio上传文件失败:{}",e.getMessage());
            return null;
        }
        return objectName;
    }
 
    /**
     * 预览图片
     * @param fileName
     * @return
     */
    public String preview(String fileName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(minioConfig.getBucketName()).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            log.error("预览文件失败:{}",e.getMessage());
        }
        return null;
    }
 
    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minioConfig.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 删除文件
     * @param fileName
     * @return
     */
    public boolean removeFile(String fileName){
        try {
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(minioConfig.getBucketName())
                    .object(fileName).build();
            minioClient.removeObject(removeObjectArgs);
            return true;
        }catch (Exception e){
            return false;
        }
    }
 
 
    /**
     * 删除文件夹
     * @param folderName
     * @return
     */
    public boolean removeFolder(String folderName){
        try {
            if(!folderName.endsWith("/")){
                folderName=folderName+"/";
            }
            ListObjectsArgs listObjectsArgs=ListObjectsArgs.builder().bucket(minioConfig.getBucketName()).prefix(folderName).build();
 
            Iterable<Result<Item>> results = minioClient.listObjects(listObjectsArgs);
            List<DeleteObject> objectNames=new ArrayList<>();
            for(Result<Item> result:results){
                objectNames.add(new DeleteObject(result.get().objectName()));
            }
            if(!objectNames.isEmpty()) {
                RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket(minioConfig.getBucketName())
                        .objects(objectNames).build();
                Iterable<Result<DeleteError>> results1 = minioClient.removeObjects(removeObjectsArgs);
                for (Result<DeleteError> result : results1) {
                    DeleteError error = result.get();
                    log.error("Error in deleting object {},{}", error.objectName(), error.message());
                }
            }
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(minioConfig.getBucketName())
                    .object(folderName).build();
            minioClient.removeObject(removeObjectArgs);
            return true;
        }catch (Exception e){
            return false;
        }
    }
 
 
 
}