package com.iflytek.file.manage.service; import com.alibaba.fastjson2.JSON; import com.iflytek.file.manage.config.MinioConfig; import com.iflytek.file.manage.exception.UtilException; import io.minio.*; import io.minio.http.Method; import io.minio.messages.Bucket; import io.minio.messages.Item; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.FastByteArrayOutputStream; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; @Service public class FileManagementService { private static final Logger log = LoggerFactory.getLogger(FileManagementService.class); @Resource private MinioClient minioClient; @Resource private MinioConfig minioConfig; /** * 查看存储bucket是否存在 * * @return boolean */ public boolean bucketExists(String bucketName) { try { return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 创建存储bucket * * @return Boolean */ public boolean createBucket(String bucketName) { try { if (!bucketExists(bucketName)) { minioClient.makeBucket(MakeBucketArgs.builder() .bucket(bucketName) .build()); // StringBuilder builder = new StringBuilder(); // builder.append("{\n"); // builder.append(" \"Statement\": [\n"); // builder.append(" {\n"); // builder.append(" \"Action\": [\n"); // builder.append(" \"s3:GetBucketLocation\",\n"); // builder.append(" \"s3:ListBucket\"\n"); // builder.append(" ],\n"); // builder.append(" \"Effect\": \"Allow\",\n"); // builder.append(" \"Principal\": \"*\",\n"); // builder.append(" \"Resource\": \"arn:aws:s3:::"); // builder.append(bucketName); // builder.append("\"\n"); // builder.append(" },\n"); // builder.append(" {\n"); // builder.append(" \"Action\": \"s3:GetObject\",\n"); // builder.append(" \"Effect\": \"Allow\",\n"); // builder.append(" \"Principal\": \"*\",\n"); // builder.append(" \"Resource\": \"arn:aws:s3:::"); // builder.append(bucketName); // builder.append("/myobject*\"\n"); // builder.append(" }\n"); // builder.append(" ],\n"); // builder.append(" \"Version\": \""); // builder.append(LocalDate.now()); // builder.append("\"\n"); // builder.append("}\n"); // minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(builder.toString()).build()); log.info("buckets:【{}】,创建[readwrite]策略成功!", bucketName); } else { log.info("minio bucket->>>【{}】already exists", bucketName); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 删除存储bucket * * @return Boolean */ public boolean removeBucket(String bucketName) { try { minioClient.removeBucket(RemoveBucketArgs.builder() .bucket(bucketName) .build()); log.debug("删除存储成功!"); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 获取全部bucket */ public String getAllBuckets() { try { List<Bucket> buckets = minioClient.listBuckets(); List<BucketInfo> bucketInfos = new ArrayList<>(); for (Bucket bucket : buckets) { BucketInfo bucketInfo = new BucketInfo(); bucketInfo.setBucketName(bucket.name()); bucketInfo.setCreateDate(bucket.creationDate().toString()); bucketInfos.add(bucketInfo); } return JSON.toJSONString(bucketInfos); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 文件上传 * * @param file 文件 * @param bucketName * @return Boolean */ public String upload(MultipartFile file, String bucketName) throws UtilException { String originalFilename = file.getOriginalFilename(); if (Objects.isNull(originalFilename)) { throw new UtilException("源文件不存在!"); } String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); StringBuilder sb = new StringBuilder(); String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM/dd")); sb.append(date).append("/").append(objectName); //检查bucket是否存在,不存在则创建 createBucket(bucketName); try { PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(sb.toString()) .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build(); //文件名称相同会覆盖 minioClient.putObject(objectArgs); } catch (Exception e) { e.printStackTrace(); return null; } return getObjectPrefixUrl(bucketName) + originalFilename; } /** * 预览图片 * * @param objectName * @return */ public String preview(String objectName, String bucketName) { // 查看文件地址 GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(objectName).method(Method.GET).build(); try { return minioClient.getPresignedObjectUrl(build); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 文件下载 * * @param objectName 文件名称 * @param res response * @param bucketName * @return Boolean */ public void download(String objectName, HttpServletResponse res, String bucketName) { GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName) .object(objectName).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.addHeader("Content-Disposition", "attachment;objectName=" + objectName); try (ServletOutputStream stream = res.getOutputStream()) { stream.write(bytes); stream.flush(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 查看文件对象 * * @return 存储bucket内文件对象信息 */ public String getAllObjectsByBucketName(String bucketName) { Iterable<Result<Item>> results = minioClient.listObjects( ListObjectsArgs.builder().bucket(bucketName).build()); Set<String> set = new HashSet<>(); try { for (Result<Item> result : results) { Item item = result.get(); if (item.isDir()) { //最后一位是/则为文件夹 totalFile(bucketName, item.objectName(), set); } else { set.add(item.objectName()); } } } catch (Exception e) { e.printStackTrace(); return ""; } return JSON.toJSONString(set); } //递归取得全部文件 public void totalFile(String bucketName, String folder, Set<String> set) { try { Iterable<Result<Item>> listObjects = minioClient.listObjects(ListObjectsArgs.builder() .bucket(bucketName).prefix(folder).build()); for (Result<Item> result : listObjects) { Item item = result.get(); if (item.isDir()) { //最后一位是/则为文件夹 totalFile(bucketName, item.objectName(), set); } else { set.add(item.objectName()); } } } catch (Exception e) { e.printStackTrace(); } } /** * 文件url前半段 * * @param bucket 桶 * @return 前半段 */ public String getObjectPrefixUrl(String bucket) { return String.format("%s/%s/", minioConfig.getUrl(), bucket); } /** * 删除 * * @param objectName * @return * @throws Exception */ public boolean remove(String objectName, String bucketName) { try { minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build()); } catch (Exception e) { return false; } return true; } static class ObjectInfo { private String objectName; private boolean isDir; public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public boolean isDir() { return isDir; } public void setDir(boolean dir) { isDir = dir; } } static class BucketInfo { private String bucketName; private String createDate; public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } } }
标签:return,String,builder,bucket,util,bucketName,append,minio From: https://www.cnblogs.com/goPush/p/17132377.html