腾讯云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=********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); }}

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

(0)

相关推荐

  • 腾讯云主要产品都有哪些?

    腾讯云主要产品都有哪些? 总体来说,腾讯云包括云服务器.云数据库.CDN.云安全.万象更新图片和云点播等产品. 通过访问腾讯的云平台,开发者可以降低初始创业成本,更容易应对来自服务器,存储和带宽的压力 ...

  • 使用picgo和阿里云oss对象存储搭建一个自动上传的图床工具

    目录 准备 在开始搭建之前,我们需要准备一些东西 第一个我们要有一个阿里云对象存储oss 对象存储资源包还是很便宜的,一块钱一个月,很嗨皮 不过阿里云之后要收流量费,不过也不是很贵,我用oss小半年了 ...

  • 一张图看懂腾讯云对象存储COS数据处理能力升级

    对象存储COS全新升级云端数据处理服务,支持海量数据处理,使用方式快捷灵活,涵盖在线教育.电商网站等场景,充分挖掘数据价值. 通过一张图来了解一下吧: 更多腾讯云对象存储(COS)相关知识可以关注官方 ...

  • 腾讯云对象存储COS应用类型介绍

    腾讯云对象存储COS应用类型介绍 腾讯云对象存储 COS 提供多种类别的云端存储服务,用户可以根据不同的业务类型搭配使用,包括用于频繁访问数据的标准存储.用于不频繁访问数据的低频存储.下面小编赵一八笔 ...

  • 对话天翼云江峰:“死磕”对象存储的用户成本

    补足劣势,放大自己的优势 " 作者 | 王德清 出品 | 雷锋网产业组 随着互联网以及移动互联网的兴起,非结构化数据呈现指数级增长,存储容量成为了大多数生成和使用大量非结构化数据的用户和企业 ...

  • 利用华为云对象存储迁移服务快速迁移其他对象存储数据

    如果我们有在处理大量的静态文件的时候,比如文件下载和图片库的时候肯定是需要用到对象存储的.一来我们直接放在第三方存储中比较安全,速度比较快,最为主要的原因是转移的时候比较方便.如果我们都存储在服务器中 ...

  • 阿里云对象存储OSS开通流程及使用方法

    一.对象存储OSS 为了解决海量数据存储与弹性扩容,采用云存储的解决方案- 阿里云OSS. 二.开通"对象存储OSS"服务 (1)申请阿里云账号 网址: https://www.a ...

  • 上手简单、多重加密,绿联个人云评测:存储原来可以这么省心

    如今手机.电脑的可用空间越来越少,资料如何存放在各个设备,成了很多用户头疼的问题.之前一直习惯用网盘,但网盘似乎一直在挑战用户的底线,体验实在是不好,而且文件安全问题堪忧. 朋友推荐我买一台NAS,我 ...

  • (40条消息) 基于腾讯云的 Rust 和 WebAssembly 函数即服务

    腾讯云云函数 (SCF) 已经支持十多种编程语言和运行时框架.腾讯云最近发布的 SCF custom runtime(自定义运行时)更进一步 -- SCF 现在可以支持用任何编程语言编写的函数. 本文 ...

  • 腾讯云技术支持爱丁堡大学研究教学

    深圳讯    腾讯公司旗下云业务品牌腾讯云5月5日公布,与苏格兰爱丁堡大学签署合作备忘录,将透过云产品及云技术支持爱丁堡大学的研究及教学,以巩固该校于研究的技术发展及人才培训. 腾讯云将为爱丁堡大学的 ...