青羊经侦大队-数据平台
wl
2022-08-16 1fb2cfb2bcb152bee03f8a332700241693cfd9b6
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
package com.example.jz.service.impl;
 
import cn.hutool.core.util.IdUtil;
import com.example.jz.config.MinIOConfig;
import com.example.jz.exception.BusinessException;
import com.example.jz.service.MinIOService;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.UploadObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
 
@Service
public class MinIOServiceImpl implements MinIOService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinIOConfig minIOConfig;
 
    @Override
    public String getPreviewFileUrl(String fileName) {
        String res = null;
        try {
            res = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(minIOConfig.getBucketName())
                            .object(fileName)
                            .build());
        } catch (Exception e) {
            throw new BusinessException("获取文件预览地址失败");
        }
        return res;
    }
 
    @Override
    public String upload(MultipartFile file) {
        String objectName = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            objectName = sdf.format(new Date()) + "/" + IdUtil.simpleUUID() + "." + file.getContentType().split("/")[1];
            PutObjectOptions putObjectOptions = new PutObjectOptions(file.getInputStream().available(), -1);
            putObjectOptions.setContentType(file.getContentType());
            minioClient.putObject(minIOConfig.getBucketName(), objectName, file.getInputStream(), putObjectOptions);
        } catch (Exception e) {
            throw new BusinessException("上传文件失败");
        }
        return objectName;
    }
 
    @Override
    public Boolean delete(String fileName) {
        try {
            minioClient.removeObject(minIOConfig.getBucketName(), fileName);
        } catch (Exception e) {
            throw new BusinessException("删除文件失败");
        }
        return true;
    }
}