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

在这里插入图片描述

1,申请key和密钥

2,引入依赖

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

3,工具类

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,获取的文件地址有时间限制,过期后需要重新获取

相关推荐

  1. python3实现gitlab备份文件COS

    2024-01-13 10:20:04       30 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-13 10:20:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-13 10:20:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-13 10:20:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-13 10:20:04       18 阅读

热门阅读

  1. 30天精通Nodejs--第十五天:Websocket

    2024-01-13 10:20:04       34 阅读
  2. 深度学习基础教程

    2024-01-13 10:20:04       28 阅读
  3. 「HDLBits题解」Module add

    2024-01-13 10:20:04       29 阅读
  4. 在Python中调用狄拉克gamma矩阵

    2024-01-13 10:20:04       29 阅读
  5. leaflet聚类——leaflet.markercluster

    2024-01-13 10:20:04       28 阅读
  6. 单链表与循环链表创建

    2024-01-13 10:20:04       37 阅读
  7. 关于人工智能的浅见

    2024-01-13 10:20:04       34 阅读
  8. Python字符串的编码和解码

    2024-01-13 10:20:04       30 阅读
  9. Scipy 中级教程——图像处理

    2024-01-13 10:20:04       34 阅读
  10. 前端笔试题(一)

    2024-01-13 10:20:04       32 阅读