1、SDK

 <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.6.24</version>
        </dependency>

        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
            <version>3.1.62</version><!-- 注:这里只是示例版本号,请获取并替换为 最新的版本号 -->
        </dependency>

2、工具类代码

import com.alibaba.fastjson.JSON;
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.region.Region;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * @author Created by 谭健 on 2020/9/18. 星期五. 14:00.
 * © All Rights Reserved.
 */
public class COSUtils {


	// id 和 密钥  secretKey 这个
    private static final String SID = "****";
    private static final String SK = "****";

    private static final COSCredentials cred = new BasicCOSCredentials(SID, SK);

    private static final Region region = new Region("ap-nanjing");
    private static final ClientConfig clientConfig = new ClientConfig(region);

    public static final String DOMAIN = "https://public-1301924604.cos.ap-nanjing.myqcloud.com/";

    /**
     * 传到 COS
     *
     * @param inputStream 输入流
     * @param key         文件名
     */
    public static String upload(InputStream inputStream, String key) {
        //  生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        // 指定要上传到的存储桶
        String bucketName = "public-1301924604";
        // 指定要上传到 COS 上对象键
        if (Objects.isNull(key)) {
            key = UUID.randomUUID().toString();
        }
        ObjectMetadata metadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        System.out.println(JSON.toJSONString(putObjectResult));
        return DOMAIN + key;
    }



}

3、使用示例

public static void main(String[] args) {

        // 示例代码
        File localFile = new File("C:\\Users\\A-PC\\Desktop\\1.txt");

        try {
            // 返回文件地址
            String upload = upload(new FileInputStream(localFile), "1.txt");
            System.out.println(upload);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }