1、application.yml
可以写在配置文件里
tencent: cos: #腾讯云的SecretId secretId: A******************68 #腾讯云的SecretKey secretKey: 7****************R #腾讯云的bucket (存储桶) bucket: ****-****-********* #腾讯云的region(bucket所在地区) region: ap-beijing #腾讯云的allowPrefix(允许上传的路径) # allowPrefix: /* #腾讯云的临时密钥时长(单位秒) durationSeconds: 1800 #腾讯云的访问基础链接: baseUrl: https://****-****-*******.cos.ap-beijing.myqcloud.com
2、maven引入
pom.xml
<dependency> <groupId>com.tencentcloudapi</groupId> <artifactId>tencentcloud-sdk-java</artifactId> <version>3.1.139</version> </dependency> <!-- 腾讯云cos sdk --> <dependency> <groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId> <version>5.6.24</version> </dependency> <!-- 腾讯云cos-获取临时秘钥的 --> <dependency> <groupId>com.tencent.cloud</groupId> <artifactId>cos-sts-java</artifactId> <version>3.0.8</version> </dependency>
3、代码
TencentUploadUtil.java
package com.home.app.common.utils.file; import com.home.app.common.utils.IDKeyUtil; import com.home.app.common.utils.StringUtils; import com.home.app.common.utils.config.Global; 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.TreeMap; /** * 腾讯云 cos工具类 */ 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 { //设置 获取到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"); } /** * 上传文件 使用临时密钥上传 * * @param filePath 文件服务器下的根路径,即key,如: doc/picture.jpg * @param file * @return 成功返回文件路径,失败返回null */ public static String 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 = 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, filePath, 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 + filePath; } catch (CosServiceException e) { //失败,抛出 CosServiceException e.printStackTrace(); } catch (CosClientException e) { //失败,抛出 CosClientException e.printStackTrace(); } finally { // 关闭客户端 cosclient.shutdown(); //返回文件的网络访问url System.err.println(rtValue); return rtValue; } } /** * 生成临时密钥 * * 官网demo:https://cloud.tencent.com/document/product/436/14048 * @return */ private static JSONObject getTempKey() { JSONObject credential = new JSONObject(); TreeMap<String, Object> config = new TreeMap<String, Object>(); 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 = 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); credential = CosStsClient.getCredential(config); //成功返回临时密钥信息,如下打印密钥信息 //LogManager.debug(TAG, credential.toString()); System.out.println(credential); } catch (Exception e) { //失败抛出异常 throw new IllegalArgumentException("no valid secret !"); } return credential; } /** * 上传测试 **/ public static void main(String[] args) { //创建文件 File file = new File("D:\\1385383488367.jpg"); //第一种:固定密钥 /** * 如果filePath是空或者是null,就以当前日期的形式存放 如:yyyy/yyyymmdd/xxx.文件后缀 * 如果指定文件夹:如 ttt/ * ps:要加斜线 / * 表示存放在目录下的ttt文件夹下 **/ uploadFile(file,null); // uploadFile(file,"ttt/"); } }
Global.java
package com.home.app.common.utils.config; import com.home.app.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; /** * 全局配置类 */ @Component public class Global { private static final Logger log = LoggerFactory.getLogger(Global.class); private static String NAME = "application.yml" ; /** * 当前对象实例 */ private static Global global; /** * 保存全局属性值 */ private static Map<String, String> map = new HashMap<String, String>(); private Global() { } /** * 静态工厂方法 */ public static synchronized Global getInstance() { if (global == null) { global = new Global(); } return global; } /** * 获取配置 */ public static String getConfig(String key) { String value = map.get(key); if (value == null) { Map<?, ?> yamlMap = null; try { yamlMap = YamlUtil.loadYaml(NAME); value = String.valueOf(YamlUtil.getProperty(yamlMap, key)); map.put(key, value != null ? value : StringUtils.EMPTY); } catch (FileNotFoundException e) { log.error("获取全局配置异常 {}", key); } } return value; } }