当前位置:   article > 正文

文件存储MinIO读写工具类_objectwriteresponse

objectwriteresponse

内容读工具类MinioReadUtils

  1. package com.assoft.fmc.common.utils;
  2. import com.assoft.fmc.common.form.ItemData;
  3. import io.minio.*;
  4. import io.minio.http.Method;
  5. import io.minio.messages.Bucket;
  6. import io.minio.messages.Item;
  7. import java.io.BufferedInputStream;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.net.URLEncoder;
  11. import java.time.ZonedDateTime;
  12. import java.time.format.DateTimeFormatter;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import java.util.concurrent.TimeUnit;
  16. import javax.servlet.http.HttpServletResponse;
  17. import com.assoft.fmc.common.constant.MinioConstants;
  18. import org.springframework.util.StringUtils;
  19. public class MinioReadUtils {
  20. private static MinioClient minioClient;
  21. public static List<String> docList;
  22. static {
  23. initMinioClientInstance();
  24. }
  25. private static synchronized void initMinioClientInstance() {
  26. if (minioClient == null) {
  27. minioClient = MinioClient.builder()
  28. .endpoint(MinioConstants.FLOW_MINIO_IP, MinioConstants.FLOW_MINIO_PORT, false) // https or not
  29. .credentials(MinioConstants.FLOW_ACCESS_KEY_WRITE, MinioConstants.FLOW_SECRET_KEY_WRITE).build();
  30. }
  31. }
  32. /**
  33. * 从bucket获取指定对象的输入流,后续可使用输入流读取对象 getObject与minio server连接默认保持5分钟, 每隔15s由minio
  34. * server向客户端发送keep-alive check,5分钟后由客户端主动发起关闭连接
  35. */
  36. public static InputStream getObject(String bucketName, String objectName) throws Exception {
  37. GetObjectArgs args = GetObjectArgs.builder().bucket(bucketName).object(objectName).build();
  38. return minioClient.getObject(args);
  39. }
  40. /**
  41. * 判断文件是否存在,不能判断文件夹
  42. * @param bucketName
  43. * @param objectName
  44. * @return
  45. * @throws Exception
  46. */
  47. public static boolean checkFileExist(String bucketName, String objectName) {
  48. try {
  49. StatObjectArgs args = StatObjectArgs.builder().bucket(bucketName).object(objectName).build();
  50. minioClient.statObject(args);
  51. return true;
  52. } catch (Exception e) {
  53. return false;
  54. }
  55. }
  56. /**
  57. * 获取对象的临时访问url,有效期5分钟
  58. */
  59. public static String getObjectURL(String bucketName, String objectName) throws Exception {
  60. GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(objectName)
  61. .expiry(5, TimeUnit.MINUTES).method(Method.GET).build();
  62. return minioClient.getPresignedObjectUrl(args);
  63. }
  64. /**
  65. * 从minio下载文件,直接通过response传输
  66. */
  67. public static void downloadFile(String bucketName, String objectName, HttpServletResponse response) throws Exception {
  68. String[] objList=objectName.split("/");
  69. String fileName=objList[objList.length-1];
  70. try (InputStream is = getObject(bucketName, objectName);
  71. BufferedInputStream bis = new BufferedInputStream(is);
  72. OutputStream os = response.getOutputStream()) {
  73. // try {
  74. /*
  75. * InputStream is = getObject(bucketName, filePath); BufferedInputStream bis =
  76. * new BufferedInputStream(is); OutputStream os = response.getOutputStream();
  77. */
  78. response.setContentType("application/force-download;charset=utf-8");// 设置强制下载而不是直接打开
  79. response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名
  80. byte[] buffer = new byte[1024 * 1024 * 1024]; // buffer 1M
  81. int offset = bis.read(buffer);
  82. while (offset != -1) {
  83. os.write(buffer, 0, offset);
  84. offset = bis.read(buffer);
  85. }
  86. os.flush();
  87. } catch (Exception e) {
  88. throw new RuntimeException("下载文件失败", e);
  89. }
  90. }
  91. public static List<Bucket> getAllBuckets() {
  92. try {
  93. List<Bucket> buckets = minioClient.listBuckets();
  94. return buckets;
  95. } catch (Exception e) {
  96. e.printStackTrace();
  97. }
  98. return null;
  99. }
  100. // 遍历找到桶下所有路径
  101. public static void listDocs(String bucketName,String prefix){
  102. Iterable<Result<Item>> listObjects=new ArrayList<>();
  103. if(StringUtils.hasLength(prefix)){
  104. listObjects = minioClient.listObjects(ListObjectsArgs.builder()
  105. .bucket(bucketName)
  106. .prefix(prefix)
  107. .build());
  108. }else {
  109. listObjects = minioClient.listObjects(ListObjectsArgs.builder()
  110. .bucket(bucketName)
  111. .build());
  112. }
  113. try{
  114. for (Result<Item> result : listObjects) {
  115. Item item = result.get();
  116. if(item.isDir()){
  117. docList.add(item.objectName());
  118. listDocs(bucketName,item.objectName());
  119. }
  120. }
  121. }catch (Exception e){
  122. }
  123. }
  124. public static Iterable<Result<Item>> listObjects(String bucketName,String prefix,String title,boolean recursive){
  125. try {
  126. Iterable<Result<Item>> listObjects=new ArrayList<>();
  127. if(StringUtils.hasLength(title)){
  128. listObjects = minioClient.listObjects(ListObjectsArgs.builder()
  129. .bucket(bucketName)
  130. .prefix(prefix)
  131. .startAfter(title)
  132. .build());
  133. }
  134. else if(StringUtils.hasLength(prefix)){
  135. listObjects = minioClient.listObjects(ListObjectsArgs.builder()
  136. .bucket(bucketName)
  137. .prefix(prefix)
  138. .recursive(recursive) // 递归
  139. .build());
  140. }else {
  141. listObjects = minioClient.listObjects(ListObjectsArgs.builder()
  142. .bucket(bucketName)
  143. .recursive(recursive) // 递归
  144. .build());
  145. }
  146. return listObjects;
  147. } catch (Exception e) {
  148. System.out.println("Error occurred: " + e);
  149. return null;
  150. }
  151. }
  152. }

内容写工具类MinioWriteUtils

  1. package com.assoft.fmc.common.utils;
  2. import io.minio.BucketExistsArgs;
  3. import io.minio.MakeBucketArgs;
  4. import io.minio.MinioClient;
  5. import io.minio.ObjectWriteResponse;
  6. import io.minio.PutObjectArgs;
  7. import io.minio.RemoveObjectArgs;
  8. import io.minio.SnowballObject;
  9. import io.minio.UploadObjectArgs;
  10. import io.minio.UploadSnowballObjectsArgs;
  11. import io.minio.errors.ErrorResponseException;
  12. import io.minio.errors.InsufficientDataException;
  13. import io.minio.errors.InternalException;
  14. import io.minio.errors.InvalidResponseException;
  15. import io.minio.errors.ServerException;
  16. import io.minio.errors.XmlParserException;
  17. import java.io.ByteArrayInputStream;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.FileInputStream;
  20. import java.io.FileNotFoundException;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.security.InvalidKeyException;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.time.ZonedDateTime;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Objects;
  29. import org.apache.commons.lang3.StringUtils;
  30. import org.springframework.web.multipart.MultipartFile;
  31. import com.assoft.fmc.common.constant.MinioConstants;
  32. public class MinioWriteUtils {
  33. private static MinioClient minioClient;
  34. static {
  35. initMinioClientInstance();
  36. }
  37. private static synchronized void initMinioClientInstance() {
  38. if (minioClient == null) {
  39. minioClient = MinioClient.builder().endpoint("http://"+MinioConstants.FLOW_MINIO_IP+":"+MinioConstants.FLOW_MINIO_PORT)
  40. .credentials(MinioConstants.FLOW_ACCESS_KEY_WRITE, MinioConstants.FLOW_SECRET_KEY_WRITE).build();
  41. }
  42. }
  43. private static void createBucket(String bucketName) throws InvalidKeyException, ErrorResponseException,
  44. InsufficientDataException, InternalException, InvalidResponseException, NoSuchAlgorithmException,
  45. ServerException, XmlParserException, IllegalArgumentException, IOException {
  46. BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
  47. if (!minioClient.bucketExists(bucketExistsArgs)) {
  48. MakeBucketArgs makeArgs = MakeBucketArgs.builder().bucket(bucketName).build();
  49. minioClient.makeBucket(makeArgs);
  50. }
  51. }
  52. /**
  53. * 删除对象
  54. */
  55. public static void removeObject(String bucketName, String objectName) throws Exception {
  56. RemoveObjectArgs args = RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build();
  57. minioClient.removeObject(args);
  58. }
  59. /**
  60. * 从给定输入流中传输对象并放入bucket
  61. */
  62. public static ObjectWriteResponse putObject(String bucketName, String objectName, InputStream stream, long objectSize,
  63. String contentType) throws Exception {
  64. if (StringUtils.isBlank(bucketName)) {
  65. throw new RuntimeException("bucketName不能为空!");
  66. }
  67. createBucket(bucketName);
  68. long partSize = -1; // objectSize已知,partSize设为-1意为自动设置
  69. PutObjectArgs putArgs = PutObjectArgs.builder().bucket(bucketName).object(objectName)
  70. .stream(stream, objectSize, partSize).contentType(contentType).build();
  71. ObjectWriteResponse response = minioClient.putObject(putArgs);
  72. return response;
  73. }
  74. /**
  75. * 上传MultipartFile
  76. * @param bucketName 文件存放的bucket
  77. * @param filePath 文件在bucket里的全目录
  78. * */
  79. public ObjectWriteResponse uploadFile(String bucketName, String filePath, MultipartFile file) throws Exception{
  80. return putObject(bucketName, filePath, file.getInputStream(), file.getSize(), file.getContentType());
  81. }
  82. public static ObjectWriteResponse uploadFile(String bucketName, String objectName, String fileName) throws InvalidKeyException, ErrorResponseException, InsufficientDataException, InternalException, InvalidResponseException, NoSuchAlgorithmException, ServerException, XmlParserException, IOException {
  83. createBucket(bucketName);
  84. UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build();
  85. ObjectWriteResponse response = minioClient.uploadObject(uploadObjectArgs);
  86. return response;
  87. }
  88. public static boolean uploadFiles(String bucketName, String basePath, List<String> fileNames) throws InvalidKeyException, ErrorResponseException, InsufficientDataException, InternalException, InvalidResponseException, NoSuchAlgorithmException, ServerException, XmlParserException, IllegalArgumentException, IOException {
  89. createBucket(bucketName);
  90. List<SnowballObject> objects = new ArrayList<SnowballObject>();
  91. for (String fileName : fileNames) {
  92. // File fiel = new File(basePath+fileName);
  93. //
  94. // objects.add(new SnowballObject(fileName, new f, bytes.length, ZonedDateTime.now()));
  95. byte[] bytes = fileToBytes(basePath+fileName);
  96. objects.add(new SnowballObject(fileName, new ByteArrayInputStream(bytes), bytes.length, ZonedDateTime.now()));
  97. }
  98. try {
  99. minioClient.uploadSnowballObjects(
  100. UploadSnowballObjectsArgs.builder().bucket(bucketName).objects(objects).build());
  101. return true;
  102. } catch (Exception e) {
  103. e.printStackTrace();
  104. return false;
  105. }
  106. }
  107. /**
  108. * Description 文件转字节数组
  109. * Create By Mr.Fang
  110. *
  111. * @param path 文件路径
  112. * @return byte[] 字节数组
  113. * @time 2022/7/10 10:55
  114. **/
  115. public static byte[] fileToBytes(String path) {
  116. FileInputStream fis = null;
  117. ByteArrayOutputStream bos = null;
  118. try {
  119. bos = new ByteArrayOutputStream();
  120. fis = new FileInputStream(path);
  121. int temp;
  122. byte[] bt = new byte[1024 * 10];
  123. while ((temp = fis.read(bt)) != -1) {
  124. bos.write(bt, 0, temp);
  125. }
  126. bos.flush();
  127. } catch (FileNotFoundException e) {
  128. e.printStackTrace();
  129. } catch (IOException e) {
  130. e.printStackTrace();
  131. } finally {
  132. try {
  133. if (Objects.nonNull(fis)) {
  134. fis.close();
  135. }
  136. } catch (IOException e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. return bos.toByteArray();
  141. }
  142. /* List<SnowballObject> objects = new ArrayList<SnowballObject>();
  143. objects.add(
  144. new SnowballObject(
  145. "my-object-one",
  146. new ByteArrayInputStream("hello".getBytes(StandardCharsets.UTF_8)),
  147. 5,
  148. null));
  149. objects.add(
  150. new SnowballObject(
  151. "my-object-two",
  152. new ByteArrayInputStream("java".getBytes(StandardCharsets.UTF_8)),
  153. 4,
  154. null));
  155. minioClient.uploadSnowballObjects(
  156. UploadSnowballObjectsArgs.builder().bucket("my-bucketname").objects(objects).build());*/
  157. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/110943
推荐阅读
相关标签
  

闽ICP备14008679号