腾讯云COS桶文件上传下载工具类

1,申请key和密钥

2,引入依赖

xml 复制代码
 <dependency>
     <groupId>com.qcloud</groupId>
     <artifactId>cos_api</artifactId>
     <version>5.6.24</version>
 </dependency>

3,工具类

java 复制代码
package com.example.activity.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
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.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TencentCOSUtils {
    /**
     * COS SECRETID
     */
    private static String SECRETID = "ebOzOp8NafZL2ZxKX";
    /**
     * COS SECRETKEY
     */
    private static String SECRETKEY = "WBhz59DF";
    /**
     * COS BUCKETNAME bucket的命名规则为{name}-{appid} ,存储桶名称必须为此格式
     */
    private static String BUCKETNAME = "i959430";
    private static String filePathPrefix = "/jo";

    private static String region = "ou";

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("G:\\Download\\aa.jpg");
        Map<String, String> upload = upload(file);
        System.out.println(JSONUtil.toJsonStr(upload));
    }

    /***
     * 上传文件
     * @param file
     * @return
     */
    public static Map<String, String> upload(File file) {
        COSClient cosClient = null;
        FileInputStream fileInputStream = null;
        Map<String, String> result = new HashMap<>();
        try {
            fileInputStream = new FileInputStream(file);
            //获取最后一个.的位置
            int lastIndexOf = file.getName().lastIndexOf(".");
            //获取文件的后缀名 .jpg
            String suffix = file.getName().substring(lastIndexOf);
            String filename = filePathPrefix + "/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + suffix;
            // 1 初始化用户身份信息(secretId, secretKey)。
            COSCredentials cred = new BasicCOSCredentials(SECRETID, SECRETKEY);
            // 2 设置bucket的区域, COS地域的简称请参照
            // https://cloud.tencent.com/document/product/436/6224
            // clientConfig中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者接口文档 FAQ中说明。
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 3 生成 cos 客户端。
            cosClient = new COSClient(cred, clientConfig);
            // 指定要上传到的存储桶,指定要上传到 COS 上对象键
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, filename, fileInputStream, objectMetadata);
            cosClient.putObject(putObjectRequest);
            result.put("fileName", filename);
            result.put("absolutePath", getAbsolutePath(filename));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cosClient != null) {
                // 关闭客户端(关闭后台线程)
                cosClient.shutdown();
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

 	/**
     * 下载文件
     *
     * @param fileName COS桶的文件路径
     * @param  outPath 输出路径
     */
    public static void downFile(String fileName, String outPath) {
        COSCredentials cred = new BasicCOSCredentials(SECRETID, SECRETKEY);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosClient = new COSClient(cred, clientConfig);
        GetObjectRequest getObjectRequest = new GetObjectRequest(BUCKETNAME, fileName);
        ObjectMetadata object = cosClient.getObject(getObjectRequest, new File(outPath + "/" + fileName));
        System.out.println(object);
    }

    // 删除文件
    public static void delete(String filename) {
        COSClient cosClient = null;
        try {
            // 1 初始化用户身份信息(secretId, secretKey)。
            COSCredentials cred = new BasicCOSCredentials(SECRETID, SECRETKEY);
            // 2 设置bucket的区域, COS地域的简称请参照
            // https://cloud.tencent.com/document/product/436/6224
            // clientConfig中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者接口文档 FAQ
            // 中说明。
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 3 生成 cos 客户端。
            cosClient = new COSClient(cred, clientConfig);
            cosClient.deleteObject(BUCKETNAME, filename);
        } finally {
            if (cosClient != null) {
                // 关闭客户端(关闭后台线程)
                cosClient.shutdown();
            }
        }

    }

    /***
     * 获取文件的绝对路径
     * @param fileName 文件名称
     * @return url
     */
    public static String getAbsolutePath(String fileName) {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(SECRETID, SECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // 设置URL过期时间为1小时 60*60*1000()
        Date expiration = new Date(System.currentTimeMillis() + 60 * 60 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, fileName);
        // 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(5分钟)
        generatePresignedUrlRequest.setExpiration(expiration);
        String url = cosclient.generatePresignedUrl(generatePresignedUrlRequest).toString();
        return url;
    }

}

4,注意事项

1,SECRETID和SECRETKEY 需要有读写权限

2,获取的文件地址有时间限制,过期后需要重新获取

相关推荐
清静诗意2 天前
使用 Certbot 在腾讯云生成 Let’s Encrypt 通配符证书完整教程
腾讯云·ssl证书
Front_Yue2 天前
Spring Boot 实战:腾讯云 COS 高级特性——断点续传与进度监控
spring boot·腾讯云·腾讯云cos
2401_865854883 天前
腾讯云新出的Clawdbot怎么样
云计算·腾讯云
G31135422733 天前
IM即时通讯实现原理
腾讯云
咕噜企业分发小米5 天前
腾讯云IM如何与第三方实时音频服务集成?
云计算·音视频·腾讯云
咕噜企业分发小米6 天前
腾讯云IM与TRTC集成时,如何优化用户体验?
云计算·腾讯云
咕噜企业分发小米6 天前
腾讯云IM的优点
云计算·腾讯云
咕噜企业分发小米6 天前
腾讯云im实时音频
云计算·音视频·腾讯云
马猴烧酒.7 天前
JAVA后端对象存储( 图片分享平台)详解
java·开发语言·spring·腾讯云
咕噜企业分发小米8 天前
腾讯云在多云管理工具上如何实现合规性要求?
java·云计算·腾讯云