阅读 235

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

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

叮当哥之前买了一年的腾讯云服务器,昨日偶然发现腾讯云送了叮当哥半年的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=Dug3RhGtKp8Df4FgAKt7H1ivGH7kfDiJ6UEo
# 腾讯云的SecretKey(永久的,可在控制台开启或关闭)
tencent.SecretKey=cGUanub0FYl9pQmpkU3YpyRpB93NdBXf
# 腾讯云的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);
    }
}

复制代码

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


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐