技术共享

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

2024-07-06

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

对象存储OSS工具类

在这里插入图片描述

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