天天看點

springboot整合minio

文章首推

  • ​​支付寶接口對接​​
  • ​​高德地圖調用​​
  • ​​驗證碼登入​​
  • ​​QQ郵箱登入​​

今日主題:springboot整合minio

他是對象存儲服務OSS(Object Storage Service)是一種海量、安全、低成本、高可靠的雲存儲服務,适合存放任意類型的檔案。容量和處理能力彈性擴充,多種存儲類型供選擇,全面優化存儲成本,目前在很多公司來說,一般檔案上傳都是用的這個方案來解決的。

開始

1、進入官網:​

​https://min.io/​

​​

springboot整合minio
在cmd視窗中,指令行進行minio.exe所在的檔案夾,輸入如下指令 server後面的位址是你圖檔上傳之後的存儲目錄
minio.exe server E:\minio      
springboot整合minio

因為這裡api端口是​​

​9000​

​​,是以下面的yml需要配置​

​9000​

​端口

​accessKey​

​​和​

​secretKey​

​​需要根據啟動的視窗上的值進行配置​

​bucketName​

​這個需要自己建立

2、啟動成功後,通路:​

​127.0.0.1:9000/minio​

​​,可以進入到minio的控制台

springboot整合minio

我們可以在控制台建立​​

​bucketName​

​,當然也可以用代碼建立

​create bucket​

​​

springboot整合minio
springboot整合minio
springboot整合minio

其實這個​​

​bucketName​

​​就是檔案夾的意思,我們要把檔案上傳到哪個​

​bucketName​

​,就是要把檔案上傳到對應的目錄下。

​如果需要使用minio,他的服務一定要打開。​

yml配置

spring:
  # 配置檔案上傳大小限制
  servlet:
    multipart:
      max-file-size: 200MB
      max-request-size: 200MB
minio:
  endpoint: http://127.0.0.1:9000
  accessKey: minioadmin
  secretKey: minioadmin
  bucketName: test
      

寫配置類

注冊minio用戶端,以便在代碼中使用用戶端上傳檔案。

@Data
@Component
public class MinIoClientConfig {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    /**
     * 注入minio 用戶端
     * @return
     */
    @Bean
    public MinioClient minioClient(){

        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

}      

工具類

@Data
public class ObjectItem {
    private String objectName;
    private Long size;
}      
/**
 * @description:minio工具類
 * @version:3.0
 */
@Component
public class MinioUtilS {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;
    /**
     * description: 判斷bucket是否存在,不存在則建立
     *
     * @return: void
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立存儲bucket
     * @param bucketName 存儲bucket名稱
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存儲bucket
     * @param bucketName 存儲bucket名稱
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * description: 上傳檔案
     *
     * @param multipartFile
     * @return: java.lang.String

     */
    public List<String> upload(MultipartFile[] multipartFile) {
        List<String> names = new ArrayList<>(multipartFile.length);
        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            if (split.length > 1) {
                fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
            } else {
                fileName = fileName + System.currentTimeMillis();
            }
            InputStream in = null;
            try {
                in = file.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(in, in.available(), -1)
                        .contentType(file.getContentType())
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            names.add(fileName);
        }
        return names;
    }

    /**
     * description: 下載下傳檔案
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    public ResponseEntity<byte[]> download(String fileName) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封裝傳回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    /**
     * 檢視檔案對象
     * @param bucketName 存儲bucket名稱
     * @return 存儲bucket内檔案對象資訊
     */
    public List<ObjectItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<ObjectItem> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                ObjectItem objectItem = new ObjectItem();
                objectItem.setObjectName(item.objectName());
                objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    /**
     * 批量删除檔案對象
     * @param bucketName 存儲bucket名稱
     * @param objects 對象名稱集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }


}
      

控制器

@RestController
@Slf4j
public class MinioController {
    @Autowired
    private MinIoUtil minIoUtil;
    @Autowired
    private MinioUtilS minioUtilS;
    @Value("${minio.endpoint}")
    private String address;
    @Value("${minio.bucketName}")
    private String bucketName;

    @PostMapping("/upload")
    public Object upload(MultipartFile file) {
       
        List<String> upload = minioUtilS.upload(new MultipartFile[]{file});

        return address+"/"+bucketName+"/"+upload.get(0);
    }

}
      

繼續閱讀