前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >腾讯云COS对象存储的简单使用

腾讯云COS对象存储的简单使用

作者头像
宋先生
发布2019-07-18 15:04:50
18.8K1
发布2019-07-18 15:04:50
举报

叮当哥之前买了一年的腾讯云服务器,昨日偶然发现腾讯云送了叮当哥半年的cos对象存储服务器,于是就撸起袖子传了几张珍藏的大图上去,现将其上传的简单使用步骤总结一波(其它操作参加官方SDK文档API)。

说明:这里叮当哥使用的是生成临时密钥的方式(好处多多哦)

第一步:创建Maven工程并导入相关坐标

<!-- 1.添加腾讯云指定的仓库地址 -->
    <repositories>
        <repository>
            <id>bintray-qcloud-maven-repo</id>
            <name>qcloud-maven-repo</name>
            <url>https://dl.bintray.com/qcloud/maven-repo/</url>
            <layout>default</layout>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencies>
        <!-- 2.腾讯云sdk的 -->
        <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.5.3</version>
        </dependency>
        <!-- 2.获取临时秘钥的 -->
        <dependency>
            <groupId>com.tencent.cloud</groupId>
            <artifactId>cos-sts-java</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!-- 3.json处理包的 -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
    </dependencies>

第二步:创建腾讯云cos服务器的配置文件(tencent.properties)

# 这些配置在腾讯云控制台都可查到(使用时替换为你自己的)
# 腾讯云的SecretId(永久的,可在控制台开启或关闭)
tencent.SecretId=********H1ivGH7kfDiJ6UEo
# 腾讯云的SecretKey(永久的,可在控制台开启或关闭)
tencent.SecretKey=********0FYl9pQmpkU3YpyRpB93NdBXf
# 腾讯云的bucket (存储桶)
tencent.bucket=dintalk-1228321366
# 腾讯云的region(bucket所在地区)
tencent.region=ap-beijing
# 腾讯云的allowPrefix(允许上传的路径)
tencent.allowPrefix=*
# 腾讯云的临时密钥时长(单位秒)
tencent.durationSeconds=1800
# 腾讯云的访问基础链接:
tencent.baseUrl= https:/dintalk-1228321366.cos.ap-beijing.myqcloud.com/

第三步:创建腾讯cos上传工具类

package cn.dintalk.util;

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.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.tencent.cloud.CosStsClient;
import org.json.JSONObject;

import java.io.File;
import java.util.ResourceBundle;
import java.util.TreeMap;

/**
 * 腾讯云cos服务器上传工具类
 * @author Mr.song
 * @date 2019/06/08 20:52
 */
public class TencentUploadUtil {

    //腾讯云的SecretId
    private static String secretId;
    //腾讯云的SecretKey
    private static String secretKey;
    //腾讯云的bucket (存储桶)
    private static String bucket;
    //腾讯云的region(bucket所在地区)
    private static String region;
    //腾讯云的allowPrefix(允许上传的路径)
    private static String allowPrefix;
    //腾讯云的临时密钥时长(单位秒)
    private static String durationSeconds;
    //腾讯云的访问基础链接:
    private static String baseUrl;
  //读取配置文件,初始化配置
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("properties/tencent");
        secretId = bundle.getString("tencent.SecretId");
        secretKey = bundle.getString("tencent.SecretKey");
        bucket = bundle.getString("tencent.bucket");
        region = bundle.getString("tencent.region");
        allowPrefix = bundle.getString("tencent.allowPrefix");
        durationSeconds = bundle.getString("tencent.durationSeconds");
        baseUrl = bundle.getString("tencent.baseUrl");
    }

    /**
     * 上传文件
     *
     * @param path 文件服务器下的根路径,即key,如: doc/picture.jpg
     * @param file
     * @return 成功返回文件路径,失败返回null
     */
    public static String uploadFile(String path, File file) {
        //获取临时密钥
        JSONObject temp = getTempKey();
        // 用户基本信息:解析临时密钥中的相关信息
        String tmpSecretId = temp.getJSONObject("credentials").getString("tmpSecretId");   
        String tmpSecretKey = temp.getJSONObject("credentials").getString("tmpSecretKey");  
        String sessionToken = temp.getJSONObject("credentials").getString("sessionToken");  

        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(tmpSecretId, tmpSecretKey);
        // 2 设置 bucket 区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成 cos 客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        String bucketName = bucket;
        // 上传 object, 建议 20M 以下的文件使用该接口
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, file);
        // 设置 x-cos-security-token header 字段
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setSecurityToken(sessionToken);
        putObjectRequest.setMetadata(objectMetadata);
        String rtValue = null;
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // 成功:putobjectResult 会返回文件的 etag
            String etag = putObjectResult.getETag();
            rtValue = baseUrl + path;
        } catch (CosServiceException e) {
            //失败,抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败,抛出 CosClientException
            e.printStackTrace();
        } finally {
            // 关闭客户端
            cosclient.shutdown();
            //返回文件的网络访问url
            return rtValue;
        }
    }

    /**
     * 生成临时密钥
     *
     * @return
     */
    private static JSONObject getTempKey() {
        TreeMap<String, Object> config = new TreeMap<String, Object>();
        try {//使用永久密钥生成临时密钥
            config.put("SecretId", secretId);
            config.put("SecretKey", secretKey);
            config.put("durationSeconds", Integer.parseInt(durationSeconds));
            config.put("bucket", bucket); 
            config.put("region", region);
            config.put("allowPrefix", allowPrefix);
            //密钥的权限列表,其他权限列表请看
            //https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);
            JSONObject credential = CosStsClient.getCredential(config);
            //成功返回临时密钥信息,如下打印密钥信息
            System.out.println(credential);
            return credential;
        } catch (Exception e) {
            //失败抛出异常
            throw new IllegalArgumentException("no valid secret !");
        }
    }
}

Tips:如果整合Spring,读取配置可以使用注解的方式哦

  • 类上 @PropertySource("classpath:properties/tencent.properties") ,
  • 属性上 @Value(“{tencent.SecretId}”)。

第四步:测试上传一张图片

import cn.dintalk.util.TencentUploadUtil;
import java.io.File;

/**
 * 测试文件上传
 * @author Mr.song
 * @date 2019/06/08 21:58
 */
public class TestUpload {
    public static void main(String[] args) {
        //1.创建文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\2.jpg");
        //2.调用方法,传入要在服务器上保存的目录及文件名    和  文件
        TencentUploadUtil.uploadFile("dintalk/image/2.jpg",file);
    }
}

如此,图片就从桌面上愉快的转移到了腾讯云上啦!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 顶哥说 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 第一步:创建Maven工程并导入相关坐标
  • 第二步:创建腾讯云cos服务器的配置文件(tencent.properties)
  • 第三步:创建腾讯cos上传工具类
  • 第四步:测试上传一张图片
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档