• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java实现腾讯cos上传、下载、删除对象

武飞扬头像
不凡而大米、
帮助5

【java实现腾讯cos上传、下载、删除对象】

先在腾讯开通cos服务
找到对应的参数就可通过java实现功能

学新通

选择“密钥管理"-”访问密钥“-"API密钥管理”
找到参数
学新通

java代码如下

pom文件引入依赖

		<!--腾讯cos-->
        <dependency>
			<groupId>com.qcloud</groupId>
			<artifactId>cos_api</artifactId>
			<version>5.6.8</version>
			<!--排除这个slf4j-log4j12-->
			<exclusions>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-log4j12</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
package com.ruoyi.web.controller.common;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.junit.Test;
import org.springframework.context.annotation.Bean;

import java.io.File;
import java.io.IOException;

public class test11111 {

    private String secretId = "A.......";
    private String secretKey = "wk........";

    private String region = "ap-guangzhou";
    private String bucketName ="test-1314";


    public COSClient initCOSClient(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
    /**
     * 上传文件
     */
    @Test
    public void upLoad(){
        try {
            String filePath = "E:\\Downloads\\1111.png";
            // 指定要上传的文件
            File localFile = new File(filePath);
            // 指定要上传到 COS 上对象键
            String key = getFileKey(filePath);
            System.out.println("key------------"   key);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            COSClient cosClient1 = initCOSClient();
            PutObjectResult putObjectResult = cosClient1.putObject(putObjectRequest);
            // 设置权限(公开读)
            cosClient1.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

            System.out.println("上传ID:" putObjectResult.getRequestId() " " "上传时间" putObjectResult.getDateStr());

        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }

    /**
     * 生成文件路径
     *
     * @return
     */
    private String getFileKey(String originalfileName) {
        String filePath = "test/";
        //1.获取后缀名 2.去除文件后缀 替换所有特殊字符
        String fileType = originalfileName.substring(originalfileName.lastIndexOf("."));
        String fileStr = StrUtil.removeSuffix(originalfileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
        filePath  =  new DateTime().toString("yyyyMMddHHmmss")   "_"   fileStr   fileType;
        return filePath;
    }

    @Bean
    public COSClient cosClient(){
        // 1 初始化用户身份信息(secretId, secretKey)。
        COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    @Test
    public void download() throws IOException {
        // 生成 cos 客户端。
        COSClient cosClient = initCOSClient();
        // 设置要下载到的本地路径
        File downFile = new File("D:/java/project/2222.jpg");
        String key = "test/20230112173441_E__Downloads_1111.png";

        GetObjectRequest getObjectReq = new GetObjectRequest(bucketName, key);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectReq, downFile);

    }

    /**
     * 删除文件
     */
    @Test
    public void delete() {
        // 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
        COSClient cosClient = initCOSClient();
        String key = "test/20230112173441_E__Downloads_1111.png";
        try{
            cosClient.deleteObject(bucketName,key);
            System.out.println("del successfully");
        }catch (CosClientException e){
            System.out.println(e.getMessage());
        }

    }

}


学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfgkikc
系列文章
更多 icon
同类精品
更多 icon
继续加载