JAVA 对象存储OSS工具类(腾讯云)

对象存储OSS工具类

css 复制代码
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.qcloud.cos.region.Region;
import com.wangyao.common.config.TencentOssConfig;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;


@Slf4j
public class CosUtil {

    private static final TencentOssConfig CONFIG;

    private static final String RULE_STR = "imageMogr2/format/webp";

    private static final String EXT = "^(jpg|jpeg|png|gif)$";
    public static final int INT = 1024;


    static {
        CONFIG = SpringUtil.getBean(TencentOssConfig.class);
    }

    @NotNull
    private static COSClient createCosClient() {
        COSCredentials cred = new BasicCOSCredentials(CONFIG.getSecretId(), CONFIG.getSecretKey());
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion(new Region(CONFIG.getRegion()));
        return new COSClient(cred, clientConfig);
    }

    /**
     * 上传OSS 自定义 Key
     *
     * @param inputStream 文件流
     * @param key         key
     * @return String
     */
    @SuppressWarnings("unused")
    public static String upOssByKey(InputStream inputStream, String key, String fileName) {
        return upOssByKey(inputStream, key, CONFIG.getBucket(), fileName);
    }

    /**
     * 上传OSS 自定义 Key
     *
     * @param inputStream 文件流
     * @param key         key
     * @param bucket      桶名
     * @return String
     */
    public static String upOssByKey(InputStream inputStream, String key, String bucket, String fileName) {
        return upOss(inputStream, null, key, bucket, fileName);
    }

    /**
     * 上传OSS
     *
     * @param inputStream 文件流
     * @param keyPrefix   key前缀
     * @return String
     */
    @NotNull
    public static String upOss(InputStream inputStream, String keyPrefix, String fileName) {
        return upOss(inputStream, keyPrefix, CONFIG.getBucket(), fileName);
    }

    /**
     * 上传OSS
     *
     * @param file      文件
     * @param keyPrefix key前缀
     * @return String
     */
    public static String upOss(MultipartFile file, String keyPrefix, String fileName) {
        return upOss(file, keyPrefix, null, CONFIG.getBucket(), fileName);
    }

    /**
     * 上传OSS
     *
     * @param inputStream 文件流
     * @param keyPrefix   key前缀
     * @param bucket      桶名
     * @return String
     */
    public static String upOss(InputStream inputStream, String keyPrefix, String bucket, String fileName) {
        return upOss(inputStream, keyPrefix, null, bucket, fileName);
    }

    @NotNull
    @SuppressWarnings("unused")
    public static String upOssKey(InputStream inputStream, String keyPrefix, String key, String fileName) {
        return upOss(inputStream, keyPrefix, key, CONFIG.getBucket(), fileName);
    }

    /**
     * 上传网络图片到OSS
     * @param url 网络路径
     * @return String
     */
    public static String upOss(String url, String keyPrefix, String fileName) {

        try {
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);

            try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(scsf).build();) {
                HttpGet httpget = new HttpGet(url);
                HttpResponse response = client.execute(httpget);
                return upOss(response.getEntity().getContent(), keyPrefix, CONFIG.getBucket(), fileName);
            }

        } catch (Exception e) {
            log.error("上传网络图片到OSS失败:", e);
        }

        return null;

    }

    private static String upOss(InputStream inputStream, String keyPrefix, String key, String bucket, @NotNull String fileName) {

        var cosClient = createCosClient();

        var compressPath = "https://455.cos.ap-beijing.myqcloud.com/";

        key = getString(keyPrefix, key, fileName);
        log.info("key={}", key);
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(type);

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, inputStream, objectMetadata);
            if (type.toLowerCase().matches(EXT)) {
                extracted(bucket, fileName, putObjectRequest);
            }
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            String eTag = putObjectResult.getETag();
            log.info("eTag = {}", eTag);
            cosClient.shutdown();
        } catch (Exception e) {
            log.error("Cos Upload Failed. ", e);
        }

        String result = compressPath + key;
        log.info("Cos Upload Path: {}", result);
        return result;

    }

    private static String getString(String keyPrefix, String key, String fileName) {
        if (StringUtils.isBlank(key)) {
            key = StringUtils.isNotBlank(keyPrefix) ? keyPrefix + fileName : fileName;
        }
        return key;
    }

    private static void extracted(String bucket, String fileName, PutObjectRequest putObjectRequest) {
        //如果图片比较大就进行压缩。否则就直接上传
        PicOperations picOperations = new PicOperations();
        // 添加图片处理规则
        List<PicOperations.Rule> ruleList = new LinkedList<>();
        PicOperations.Rule rule = new PicOperations.Rule();
        rule.setBucket(bucket);
        rule.setFileId(fileName);
        rule.setRule(RULE_STR);
        ruleList.add(rule);
        picOperations.setRules(ruleList);
        putObjectRequest.setPicOperations(picOperations);
    }

    @SuppressWarnings("all")

    private static String upOss(@NotNull MultipartFile file, String keyPrefix, String key, String bucket, String fileName) {

        COSClient cosClient = createCosClient();

        String compressPath = "https://455.cos.ap-beijing.myqcloud.com/";

        key = getString(keyPrefix, key, fileName);
        log.info("key={}", key);
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(type);

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file.getInputStream(), objectMetadata);
            if (type.toLowerCase().matches(EXT)) {
                //如果图片比较大就进行压缩。否则就直接上传
                if (file.getSize() > INT * INT) {
                    extracted(bucket, fileName, putObjectRequest);
                }
            }
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            String eTag = putObjectResult.getETag();
            log.info("eTag = {}", eTag);
            cosClient.shutdown();
        } catch (Exception e) {
            log.error("Cos Upload Failed. ", e);
        }

        String result = compressPath + key;
        log.info("Cos Upload Path: {}", result);
        return result;

    }

}
相关推荐
汤米粥2 分钟前
小皮PHP连接数据库提示could not find driver
开发语言·php
冰淇淋烤布蕾5 分钟前
EasyExcel使用
java·开发语言·excel
拾荒的小海螺11 分钟前
JAVA:探索 EasyExcel 的技术指南
java·开发语言
Jakarta EE28 分钟前
正确使用primefaces的process和update
java·primefaces·jakarta ee
马剑威(威哥爱编程)36 分钟前
哇喔!20种单例模式的实现与变异总结
java·开发语言·单例模式
白-胖-子1 小时前
【蓝桥等考C++真题】蓝桥杯等级考试C++组第13级L13真题原题(含答案)-统计数字
开发语言·c++·算法·蓝桥杯·等考·13级
好睡凯1 小时前
c++写一个死锁并且自己解锁
开发语言·c++·算法
java—大象1 小时前
基于java+springboot+layui的流浪动物交流信息平台设计实现
java·开发语言·spring boot·layui·课程设计
yyqzjw1 小时前
【qt】控件篇(Enable|geometry)
开发语言·qt
csdn_kike1 小时前
QT Unknown module(s) in QT 以及maintenance tool的更详细用法(qt6.6.0)
开发语言·qt