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