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; } }