java cos上传 分片技术_腾讯cos 对象存储上传文件

这个博客介绍了如何使用Java实现腾讯云对象存储(COS)的分片上传功能。通过`TencentUploadUtil`类,利用临时密钥进行身份验证,并设置上传文件的元数据,确保安全有效地上传文件到指定的存储桶。
摘要由CSDN通过智能技术生成

packagecom.home.app.common.utils.file;importcom.home.app.common.utils.IDKeyUtil;importcom.home.app.common.utils.StringUtils;importcom.home.app.common.utils.config.Global;importcom.qcloud.cos.COSClient;importcom.qcloud.cos.ClientConfig;importcom.qcloud.cos.auth.BasicCOSCredentials;importcom.qcloud.cos.auth.COSCredentials;importcom.qcloud.cos.exception.CosClientException;importcom.qcloud.cos.exception.CosServiceException;importcom.qcloud.cos.model.ObjectMetadata;importcom.qcloud.cos.model.PutObjectRequest;importcom.qcloud.cos.model.PutObjectResult;importcom.qcloud.cos.region.Region;importcom.tencent.cloud.CosStsClient;importorg.json.JSONObject;importjava.io.File;importjava.util.TreeMap;/*** 腾讯云 cos工具类*/

public classTencentUploadUtil {//腾讯云的SecretId

private staticString secretId;//腾讯云的SecretKey

private staticString secretKey;//腾讯云的bucket (存储桶)

private staticString bucket;//腾讯云的region(bucket所在地区)

private staticString region;//腾讯云的allowPrefix(允许上传的路径)

private staticString allowPrefix;//腾讯云的临时密钥时长(单位秒)

private staticString durationSeconds;//腾讯云的访问基础链接:

private staticString baseUrl;//初始化

static{//设置 获取到yml配置文件的参数 Global是自己的工具类,可以取到yml配置文件的参数

secretId = Global.getConfig("tencent.cos.secretId");

secretKey= Global.getConfig("tencent.cos.secretKey");

bucket= Global.getConfig("tencent.cos.bucket");

region= Global.getConfig("tencent.cos.region");

allowPrefix= "/*";

durationSeconds= Global.getConfig("tencent.cos.durationSeconds");

baseUrl= Global.getConfig("tencent.cos.baseUrl");

}/*** 上传文件 使用临时密钥上传

*

*@paramfilePath 文件服务器下的根路径,即key,如: doc/picture.jpg

*@paramfile

*@return成功返回文件路径,失败返回null*/

public staticString uploadFile(File file,String filePath) {//获取最后一个.的位置

int lastIndexOf = file.getName().lastIndexOf(".");//获取文件的后缀名 .jpg

String suffix =file.getName().substring(lastIndexOf);//如果filePath是空或者是null,就以当前日期的形式存放 如:yyyy/yyyymmdd/xxx.文件后缀

String tempName = "";if(StringUtils.isEmpty(filePath)){

filePath= DateUtils.getDateY()+"/"+DateUtils.getDateY()+DateUtils.getDateMd()+"/"+ IDKeyUtil.generateId()+suffix;

}else{

tempName= IDKeyUtil.generateId()+suffix;

}//处理文件路径

filePath = filePath.startsWith("/") ? filePath : "/" + filePath+tempName;//获取临时密钥

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 = newBasicCOSCredentials(tmpSecretId, tmpSecretKey);//2 设置 bucket 区域

ClientConfig clientConfig = new ClientConfig(newRegion(region));//3 生成 cos 客户端

COSClient cosclient = newCOSClient(cred, clientConfig);//bucket名需包含appid

String bucketName =bucket;//上传 object, 建议 20M 以下的文件使用该接口

PutObjectRequest putObjectRequest = newPutObjectRequest(bucketName, filePath, file);//设置 x-cos-security-token header 字段

ObjectMetadata objectMetadata = newObjectMetadata();

objectMetadata.setSecurityToken(sessionToken);

putObjectRequest.setMetadata(objectMetadata);

String rtValue= null;try{

PutObjectResult putObjectResult=cosclient.putObject(putObjectRequest);//成功:putobjectResult 会返回文件的 etag

String etag =putObjectResult.getETag();

rtValue= baseUrl +filePath;

}catch(CosServiceException e) {//失败,抛出 CosServiceException

e.printStackTrace();

}catch(CosClientException e) {//失败,抛出 CosClientException

e.printStackTrace();

}finally{//关闭客户端

cosclient.shutdown();//返回文件的网络访问url

System.err.println(rtValue);returnrtValue;

}

}/*** 生成临时密钥

*

* 官网demo:https://cloud.tencent.com/document/product/436/14048*@return

*/

private staticJSONObject getTempKey() {

JSONObject credential= newJSONObject();

TreeMap config = new TreeMap();try{//替换为您的 SecretId

config.put("SecretId", secretId);//替换为您的 SecretKey

config.put("SecretKey", secretKey);//临时密钥有效时长,单位是秒,默认1800秒,最长可设定有效期为7200秒

config.put("durationSeconds", Integer.parseInt(durationSeconds));//换成您的 bucket

config.put("bucket", bucket);//换成 bucket 所在地区

config.put("region", region);//这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子:a.jpg 或者 a/* 或者 * 。//如果填写了“*”,将允许用户访问所有资源;除非业务需要,否则请按照最小权限原则授予用户相应的访问权限范围。

config.put("allowPrefix", allowPrefix);//密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限,其他权限列表请看https://cloud.tencent.com/document/product/436/31923

String[] allowActions = newString[]{//简单上传

"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);

credential=CosStsClient.getCredential(config);//成功返回临时密钥信息,如下打印密钥信息//LogManager.debug(TAG, credential.toString());

System.out.println(credential);

}catch(Exception e) {//失败抛出异常

throw new IllegalArgumentException("no valid secret !");

}returncredential;

}/*** 上传测试

**/

public static voidmain(String[] args) {//创建文件

File file = new File("D:\\1385383488367.jpg");//第一种:固定密钥

/*** 如果filePath是空或者是null,就以当前日期的形式存放 如:yyyy/yyyymmdd/xxx.文件后缀

* 如果指定文件夹:如 ttt/

* ps:要加斜线 /

* 表示存放在目录下的ttt文件夹下

**/uploadFile(file,null);//uploadFile(file,"ttt/");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值