使用minio与腾讯cos文件上传下载

废话不多多,直接上代码

第一步、引入相应包


    com.qcloud
    cos_api
    5.6.61


    io.minio
    minio
    8.2.1

第二步 、写cos与minio相关配置类

/**
 * @author 重庆阿汤哥
 * @Description: cos文件服务基础配置
 * @date 2021/11/17  13:17
 */
@Configuration
@Data
public class CosProperties {
    /**
     * 连接url
     */
    @Value("${cos.endpoint:}")
    private String endpoint;
    /**
     * 用户名
     */
    @Value("${cos.accesskey:}")
    private String accesskey;
    /**
     * 密码
     */
    @Value("${cos.secretKey:}")
    private String secretKey;
    /**
     * 桶名称
     */
    @Value("${cos.bucket:}")
    private String bucket;
    /**
     *就购买时选择的区域
     **/
    @Value("${cos.region:}")
    private String region;
    /**
     *http,https
     **/
    @Value("${cos.scheme:}")
    private String scheme;

    @Value("${cos.token:}")
    private String token;

}
/**
 * @author 重庆阿汤哥
 * @Description: minio基础信息配置
 * @date 2021/11/17  13:17
 */
@Component
@ConfigurationProperties("minio")
@Data
public class MinioProperties {
    /**
     * 连接url
     */
    private String endpoint;
    /**
     * 用户名
     */
    private String accesskey;
    /**
     * 密码
     */
    private String secretKey;
    /**
     * 
     */
    private String bucket;

}

第三步、初始客户端

/**
 * @author 重庆阿汤哥
 * @Description:文件客户端初始化配置类
 * @date 2021/11/17  13:24
 */

@Configuration
public class FileClientConfiguration {
    @Autowired
    private MinioProperties minioProperties;
    @Resource
    private CosProperties cosProperties;

    @Bean
    public MinioClient minioClient() {
        MinioClient client = MinioClient.builder().endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccesskey(), minioProperties.getSecretKey()).build();
        return client;
    }

    @Bean
    public COSClient COSClientInit() {
        COSCredentials credentials = new BasicCOSCredentials(cosProperties.getAccesskey(), cosProperties.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(cosProperties.getRegion()));
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials, clientConfig);
        return cosClient;
    }
}

 

 第四步、工具类简单封装

/**
 * @author 阿汤哥
 * @Description: 文件夹工具类
 * @date 2021/11/17  13:33
 */
@Component
@Slf4j
public class FileUploadUtils {
    @Resource
    private MinioClient minioClient;
    @Resource
    private COSClient cosClient;
    @Resource
    private MinioProperties minioProperties;
    @Resource
    private CosProperties cosProperties;
    @Resource
    private GlobalParamConfig globalParamConfig;

    /**
     * @return void
     * @Author 阿汤哥
     * @Description 文件上传
     * @Date 2021/11/17 13:41
     * @Param [file]
     **/
    public String upload(MultipartFile file) {
        String filePath = null;
        try {
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 设置存储对象名称
            filePath = sdf.format(new Date()) + "/" + filename;
              //minio  
            if (BrainConstants.FILE_UPLOAD_MINIO.equalsIgnoreCase(globalParamConfig.getFileType())) {

                String bucketName = minioProperties.getBucket();
                //创建头部信息
                Map headers = new HashMap<>();
                //添加自定义内容类型
                headers.put("Content-Type", "application/octet-stream");
                //添加存储类
                headers.put("X-Amz-Storage-Class", "REDUCED_REDUNDANCY");

                // 使用putObject上传一个文件到存储桶中
                PutObjectArgs build = PutObjectArgs.builder().bucket(bucketName).object(filePath).stream(
                        file.getInputStream(), file.getSize(), -1)
                        .headers(headers)
                        .build();

                minioClient.putObject(build);
                log.info("文件上传minio成功!");
            } else {//腾讯cos
                File varFile = MultipartFileToFile.toFile(file, filePath);
                // 将 文件上传至 COS
                PutObjectRequest objectRequest = new PutObjectRequest(cosProperties.getBucket(), filePath, varFile);
                cosClient.putObject(objectRequest);
                log.info("文件上传cos成功!");
            }
            return filePath;
        } catch (Exception e) {
            log.error("minio上传发生错误: {}!", e.getMessage());
        }
        return null;
    }

    /**
     * @return
     * @Author 阿汤哥
     * @Description 删除
     * @Date 2021/11/17 13:41
     * @Param
     **/
    public boolean delete(String filePath) {
        try {
            if (BrainConstants.FILE_UPLOAD_MINIO.equalsIgnoreCase(globalParamConfig.getFileType())) {
                String bucketName = minioProperties.getBucket();
                RemoveObjectArgs build = RemoveObjectArgs.builder().bucket(bucketName).object(filePath).build();
                minioClient.removeObject(build);
            } else {
                cosClient.deleteObject(cosProperties.getBucket(), filePath);
            }
            return true;
        } catch (Exception e) {
            log.error("minio删除发生错误: {}!", e.getMessage());
        }
        return false;
    }

    /**
     * @return
     * @Author 阿汤哥
     * @Description 下载
     * @Date 2021/11/17 13:41
     * @Param
     **/
    public InputStream dowlod(String filePath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (BrainConstants.FILE_UPLOAD_MINIO.equalsIgnoreCase(globalParamConfig.getFileType())) {
            String bucketName = minioProperties.getBucket();
            GetObjectArgs build = GetObjectArgs.builder().bucket(bucketName).object(filePath).build();
            InputStream object = minioClient.getObject(build);
            return object;
        } else {
            COSObject object = cosClient.getObject(cosProperties.getBucket(), filePath);
            COSObjectInputStream objectContent = object.getObjectContent();
            return objectContent;
        }
    }

}

你可能感兴趣的:(JAVA,docker,java,spring,boot)