java对象存储工具类

package top.yuechenc.xingchen.common.utils;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 com.tencent.cloud.CosStsClient;
import lombok.Data;
import org.json.JSONObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;/*** @description: 腾讯对象存储服务* @author: Zhiwei Wang* @create: 2020/12/30*/
@Data
@Component
@PropertySource("other.yml")
@ConfigurationProperties(prefix = "tencent")
public class CosClientTest implements InitializingBean {/*** 腾讯云的SecretId*/@Value("${secretId}")private String secretId;/*** 腾讯云的SecretKey*/@Value("${secretKey}")private String secretKey;/*** 腾讯云的bucket (存储桶)*/@Value("${bucket}")private String bucket;/*** 腾讯云的region(bucket所在地区)*/@Value("${region}")private String region;/*** 腾讯云的allowPrefix(允许上传的路径)*/@Value("${allowPrefix}")private String allowPrefix;/*** 腾讯云的临时密钥时长(单位秒)*/@Value("${durationSeconds}")private String durationSeconds;/*** 腾讯云的访问基础链接*/@Value("${baseUrl}")private String baseUrl;@Overridepublic void afterPropertiesSet() {System.out.println("================="+secretId);}/*** @param fullFileName 文件服务器下的根路径,即key,如: doc/picture.jpg* @param file* @return 成功返回文件路径, 失败返回null* @description: 使用临时秘钥上传文件* @author: Zhiwei Wang* @date: 2020/12/30 9:36*/public String keyUploadFile(String fullFileName, 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名需包含appidString bucketName = bucket;// 上传 object, 建议 20M 以下的文件使用该接口PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fullFileName, 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 会返回文件的 etagString etag = putObjectResult.getETag();rtValue = baseUrl + fullFileName;} catch (CosServiceException e) {//失败,抛出 CosServiceExceptione.printStackTrace();} catch (CosClientException e) {//失败,抛出 CosClientExceptione.printStackTrace();} finally {// 关闭客户端cosclient.shutdown();//返回文件的网络访问urlreturn rtValue;}}private void keyDownloadFile() {//获取临时密钥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);}/*** 生成临时密钥** @return*/private 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 !");}}/*** 初始化CosClient相关配置, appid、accessKey、secretKey、region** @return*/public COSClient getCosClient() {// 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 方法, 使用可参见源码或者常见问题 Java SDK 部分。Region regiona = new Region(region);ClientConfig clientConfig = new ClientConfig(regiona);// 3 生成 cos 客户端。COSClient cosClient = new COSClient(cred, clientConfig);return cosClient;}/*** 上传文件** @return*/public String uploadFile(String fullFileName, File file) {PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fullFileName, file);// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)putObjectRequest.setStorageClass(StorageClass.Standard_IA);COSClient cc = getCosClient();String etag = "";String resutl;try {PutObjectResult putObjectResult = cc.putObject(putObjectRequest);// putobjectResult会返回文件的etagetag = putObjectResult.getETag();resutl = baseUrl + fullFileName;} catch (CosServiceException e) {e.printStackTrace();resutl=e.getMessage();} catch (CosClientException e) {e.printStackTrace();resutl=e.getMessage();}finally {// 关闭客户端cc.shutdown();}return resutl;}/*** 下载文件** @param bucketName* @param path* @return*/public String downLoadFile(String bucketName, String path, String fullFileName) {File downFile = new File(fullFileName);COSClient cc = getCosClient();GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);ObjectMetadata downObjectMeta = cc.getObject(getObjectRequest, downFile);cc.shutdown();String etag = downObjectMeta.getETag();return etag;}/*** 删除文件** @param bucketName* @param path*/public void deleteFile(String bucketName, String path) {COSClient cc = getCosClient();try {cc.deleteObject(bucketName, path);} catch (CosClientException e) {e.printStackTrace();} finally {cc.shutdown();}}/*** 创建桶** @param bucketName* @return* @throws CosClientException* @throws CosServiceException*/public Bucket createBucket(String bucketName) throws CosClientException, CosServiceException {COSClient cc = getCosClient();Bucket bucket = null;try {bucket = cc.createBucket(bucketName);} catch (CosClientException e) {e.printStackTrace();} finally {}return bucket;};/*** 删除桶** @param bucketName* @throws CosClientException* @throws CosServiceException*/public void deleteBucket(String bucketName) throws CosClientException, CosServiceException {COSClient cc = getCosClient();try {cc.deleteBucket(bucketName);} catch (CosClientException e) {e.printStackTrace();} finally {}};/*** 判断桶是否存在** @param bucketName* @return* @throws CosClientException* @throws CosServiceException*/public boolean doesBucketExist(String bucketName) throws CosClientException, CosServiceException {COSClient cc = getCosClient();boolean bucketExistFlag = cc.doesBucketExist(bucketName);return bucketExistFlag;};/*** 查看桶文件** @param bucketName* @return* @throws CosClientException* @throws CosServiceException*/public ObjectListing listObjects(String bucketName) throws CosClientException, CosServiceException {COSClient cc = getCosClient();// 获取 bucket 下成员(设置 delimiter)ListObjectsRequest listObjectsRequest = new ListObjectsRequest();listObjectsRequest.setBucketName(bucketName);// 设置 list 的 prefix, 表示 list 出来的文件 key 都是以这个 prefix 开始listObjectsRequest.setPrefix("");// 设置 delimiter 为/, 即获取的是直接成员,不包含目录下的递归子成员listObjectsRequest.setDelimiter("/");// 设置 marker, (marker 由上一次 list 获取到, 或者第一次 list marker 为空)listObjectsRequest.setMarker("");// 设置最多 list 100 个成员,(如果不设置, 默认为 1000 个,最大允许一次 list 1000 个 key)listObjectsRequest.setMaxKeys(100);ObjectListing objectListing = cc.listObjects(listObjectsRequest);// 获取下次 list 的 markerString nextMarker = objectListing.getNextMarker();// 判断是否已经 list 完, 如果 list 结束, 则 isTruncated 为 false, 否则为 trueboolean isTruncated = objectListing.isTruncated();List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();for (COSObjectSummary cosObjectSummary : objectSummaries) {// get file pathString key = cosObjectSummary.getKey();// get file lengthlong fileSize = cosObjectSummary.getSize();// get file etagString eTag = cosObjectSummary.getETag();// get last modify timeDate lastModified = cosObjectSummary.getLastModified();// get file save typeString StorageClassStr = cosObjectSummary.getStorageClass();}return objectListing;}public void main(String[] args) {//uploadFile();//downLoadFile();//deleteFile();//createBucket();//deleteBucket();//doesBucketExist();//listObjects();}}

springboot配置文件

tencent:# 腾讯云的SecretId(永久的,可在控制台开启或关闭)secretId: ***# 腾讯云的SecretKey(永久的,可在控制台开启或关闭)secretKey: ***# 腾讯云的allowPrefix(允许上传的路径)allowPrefix: '*'# 腾讯云的访问基础链接:baseUrl: https://xingchen-***.cos.ap-chengdu.myqcloud.com/# 腾讯云的bucket (存储桶)bucket: xingchen-***# 腾讯云的临时密钥时长(单位秒)durationSeconds: 1800# 腾讯云的region(bucket所在地区)region: ap-chengdu

腾讯云--OOS对象存储服务--java程序封装相关推荐

  1. YII2调用天翼云OOS 对象存储服务

    前言 本文仅适用于新接触对象存储服务开发的新人,对于非常熟悉对象开发的人来说会发现其实都一样,网上有很多阿里云Oss的开发教程,甚至有composer 的安装方法,非常方便,但是如果新人接触对象存储开 ...

  2. 使用腾讯云cos对象存储服务托管静态网站

    1.开通cos对象存储服务 在腾讯云服务官网的菜单栏中找到对象存储,或者服务搜索框中搜索对象存储,都可以快捷地找到对象存储产品页面. 按提示开通相关服务即可. 开通服务之后,进入对象存储管理控制台,如 ...

  3. 腾讯云cos对象存储服务文件上传api就是一个大坑

    一.介绍 对象存储服务(Cloud Object Service)是基于腾讯多年海量服务经验,对外提供的可靠.安全.易用的海量存储服务.提供多样化接入方式,以及全国部署的上传加速集群,可以无缝衔接CD ...

  4. html5 dzzxjbd cn,UEditor实现单张图片上传至腾讯云(对象存储服务)功能(html5

    UEditor文件上传默认只支持后端语音,因为项目是前后端分离开发,所以需要前端自行实现图片上传. 这里是直接修改的 ueditor/ueditor.all.js文件 ueditor.all.js中找 ...

  5. 阿里云oos对象存储 上手快速入门

    一·要想使用阿里云oos对象存储 首先要去阿里云官网开通这个服务 点进去开通该服务 根据自己需求填写即可 二·首次开通服务后 它会给你一个AccessKey ID和AccessKey Secret记得 ...

  6. 阿里云OSS——对象存储服务(工具)

    阿里云OSS--对象存储服务(工具) 一.依赖 二.yaml配置 三.OSS工具类 四.demo演示 4.1 SpringBoot启动类 4.2 Controller接口 4.3 swagger测试 ...

  7. 如何使用阿里云国际对象存储服务自动备份

    异地备份是一项重要的安全措施.它们允许在发生硬件故障.意外删除或任何其他灾难性事件时还原数据.自动备份可提高备份过程的可靠性,并确保定期备份最近的数据. 有关阿里云国际对象存储服务自动备份的操作,今天 ...

  8. 腾讯cos做文件服务器,将腾讯云COS对象存储挂载至腾讯云服务器实现大硬盘存储...

    老蒋在前面的文章中有介绍到腾讯云COS对象存储的用途还是比较大的,有我们常见的用来当做网盘使用,也可以将用来网站静态文件分离,同时还有可以作为数据同步备份.在这篇文章中,我还准备测试商家支持将COS挂 ...

  9. 配置阿里云OSS对象存储服务

    配置阿里云OSS对象存储服务 导入阿里云OSS依赖 <dependency><groupId>com.aliyun.oss</groupId><artifac ...

  10. 腾讯云cos html,腾讯云COS对象存储基础设置全攻略记录

    腾讯云专题网在"创建腾讯云COS存储准备部署静态资源分离 及获取API授权"文章中分享到我们如何创建腾讯云COS对象存储以及获取API密钥的方法.但是,如果我们将腾讯云COS存储用 ...

最新文章

  1. 设计模式之中介者模式(Mediator)摘录
  2. 2013年下半年系统集成项目管理工程师考试试卷(回忆版)
  3. 二极管7种应用电路详解之七
  4. DropDownList控件的AutoPostBack属性的问题 选择后,值也跟着刷新
  5. python 列表拼接_【Python杂货铺】速学python基础
  6. Android MVP模式就是这么回事儿
  7. 如何为编程爱好者设计一款好玩的智能硬件(三)——该选什么样的MCU呢?
  8. java -jar 找不到引用类_怎么解决java -jar找不到主类问题
  9. 常用的友元重载运算符OSTREAM
  10. 高度为5的3阶b树含有的关键字个数_第15期:索引设计(索引组织方式 B+ 树)
  11. 13. GD32F103C8T6入门教程-定时器-3路pwm输出-刹车死区保护
  12. Redis作者谈Redis应用场景
  13. Auto 和 Decltye 的区别
  14. 华为p40为何没有搭载鸿蒙系统?
  15. Double Deep Q-Learning Netwok的理解与实现
  16. 测试人员该学习哪些Linux知识
  17. 关于CSP-J/S2019准考证下载、考点查询等问题的说明
  18. 好用的dns服务器工具有哪些?
  19. 以太网卡、IB网卡的详细介绍以及区别分析
  20. Civil3D创建装配集合

热门文章

  1. Android 沉浸式全面详解(这一篇文章就够了)
  2. idea 内存溢出问题
  3. MongoDB和MySQL常用增删改查语句
  4. jQuery cdn加速
  5. 浏览器打开html文件特别慢,打开网页慢是什么原因,教您打开网页慢怎么解决
  6. 拯救强迫症:Win11去除桌面快捷方式小箭头
  7. 迅雷下载VS2015地址,快、狠,准
  8. 阿里云要引领数据库市场?这话没毛病
  9. C# Ajax上传图片同时生成微缩图(附Demo)
  10. 博奥导出工程项目电子表格_博奥造价软件导出excel表格无数据原因-2015年基础教育年报导出的电子表格没有数据,什么原因?...