package com.gkhy.safePlatform.account.utils; import com.gkhy.safePlatform.account.model.bo.ObjectItemBO; import com.gkhy.safePlatform.account.model.constant.Constants; import com.gkhy.safePlatform.commons.config.file.MinioConfig; import com.gkhy.safePlatform.commons.utils.UUIDUtil; import io.minio.*; import io.minio.errors.*; import io.minio.http.Method; import org.apache.commons.collections.map.SingletonMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; @Component("accountMinioUtils") public class MinioUtils { @Autowired private MinioClient minioClient; @Autowired private MinioConfig minioConfig; /** * @Description: 获取文件下载地址 */ public String getAccessibleUrl(String floder,String objectName) { try { return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder() .method(Method.GET) .bucket(minioConfig.getBucketName()) .object(floder + objectName) .build()); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @Description: 获取上传文件地址 */ public ObjectItemBO getPresignedUrl(String floder, String filename) { try { String uuid = UUIDUtil.initUUID(); String fileSuffix = filename.substring(filename.lastIndexOf(".")); String today = LocalDate.now().format(Constants.DF_yyyyMMdd); StringBuilder objectName = new StringBuilder(); // eg:2022-08-24_dGyRoNUT.png objectName.append(today) .append("_") .append(uuid) .append(fileSuffix); String presignedObjectUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder() .method(Method.PUT) .bucket(minioConfig.getBucketName()) .object(floder + objectName) .expiry(60 * 10) .extraQueryParams(Collections.singletonMap("response-content-type", "application/json")) .build()); ObjectItemBO object = new ObjectItemBO(); object.setPresignedUrl(presignedObjectUrl); object.setObjectName(objectName.toString()); return object; } catch (Exception e) { e.printStackTrace(); return null; } } /** * @Description: 删除文件 */ public boolean deleteFile(String floder, String objectName) { try { minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(floder + objectName).build()); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }