对象存储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) ; } @SuppressWarnings ( "unused" ) public static String upOssByKey ( InputStream inputStream, String key, String fileName) { return upOssByKey ( inputStream, key, CONFIG.getBucket ( ) , fileName) ; } public static String upOssByKey(InputStream inputStream, String key, String bucket, String fileName) { return upOss ( inputStream, null, key, bucket, fileName) ; } @NotNull public static String upOss ( InputStream inputStream, String keyPrefix, String fileName) { return upOss ( inputStream, keyPrefix, CONFIG.getBucket ( ) , fileName) ; } public static String upOss(MultipartFile file, String keyPrefix, String fileName) { return upOss ( file, keyPrefix, null, CONFIG.getBucket ( ) , fileName) ; } 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) ; } 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; } }