說明:這里叮當哥使用的是生成臨時密鑰的方式(好處多多哦)
第一步:創建Maven工程並導入相關坐標
<!-- 1.添加騰訊雲指定的倉庫地址 --> <repositories> <repository> <id>bintray-qcloud-maven-repo</id> <name>qcloud-maven-repo</name> <url>https://dl.bintray.com/qcloud/maven-repo/</url> <layout>default</layout> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <dependencies> <!-- 2.騰訊雲sdk的 --> <dependency> <groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId> <version>5.5.3</version> </dependency> <!-- 2.獲取臨時秘鑰的 --> <dependency> <groupId>com.tencent.cloud</groupId> <artifactId>cos-sts-java</artifactId> <version>3.0.3</version> </dependency> <!-- 3.json處理包的 --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> </dependencies>
# 這些配置在騰訊雲控制台都可查到(使用時替換為你自己的) # 騰訊雲的SecretId(永久的,可在控制台開啟或關閉) tencent.SecretId=Dug3RhGtKp8Df4FgAKt7H1ivGH7kfDiJ6UEo # 騰訊雲的SecretKey(永久的,可在控制台開啟或關閉) tencent.SecretKey=cGUanub0FYl9pQmpkU3YpyRpB93NdBXf # 騰訊雲的bucket (存儲桶) tencent.bucket=dintalk-1228321366 # 騰訊雲的region(bucket所在地區) tencent.region=ap-beijing # 騰訊雲的allowPrefix(允許上傳的路徑) tencent.allowPrefix=* # 騰訊雲的臨時密鑰時長(單位秒) tencent.durationSeconds=1800 # 騰訊雲的訪問基礎鏈接: tencent.baseUrl= https:/dintalk-1228321366.cos.ap-beijing.myqcloud.com/
package cn.dintalk.util; 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.ResourceBundle; import java.util.TreeMap; /** * 騰訊雲cos服務器上傳工具類 * @author Mr.song * @date 2019/06/08 20:52 */ 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 { ResourceBundle bundle = ResourceBundle.getBundle("properties/tencent"); secretId = bundle.getString("tencent.SecretId"); secretKey = bundle.getString("tencent.SecretKey"); bucket = bundle.getString("tencent.bucket"); region = bundle.getString("tencent.region"); allowPrefix = bundle.getString("tencent.allowPrefix"); durationSeconds = bundle.getString("tencent.durationSeconds"); baseUrl = bundle.getString("tencent.baseUrl"); } /** * 上傳文件 * * @param path 文件服務器下的根路徑,即key,如: doc/picture.jpg * @param file * @return 成功返回文件路徑,失敗返回null */ public static String uploadFile(String path, 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名需包含appid String bucketName = bucket; // 上傳 object, 建議 20M 以下的文件使用該接口 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, 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 + path; } catch (CosServiceException e) { //失敗,拋出 CosServiceException e.printStackTrace(); } catch (CosClientException e) { //失敗,拋出 CosClientException e.printStackTrace(); } finally { // 關閉客戶端 cosclient.shutdown(); //返回文件的網絡訪問url return rtValue; } } /** * 生成臨時密鑰 * * @return */ private static 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 !"); } } }
-
類上 @PropertySource("classpath:properties/tencent.properties") ,
-
屬性上 @Value(“{tencent.SecretId}”)。
第四步:測試上傳一張圖片
import cn.dintalk.util.TencentUploadUtil; import java.io.File; /** * 測試文件上傳 * @author Mr.song * @date 2019/06/08 21:58 */ public class TestUpload { public static void main(String[] args) { //1.創建文件 File file = new File("C:\\Users\\Administrator\\Desktop\\2.jpg"); //2.調用方法,傳入要在服務器上保存的目錄及文件名 和 文件 TencentUploadUtil.uploadFile("dintalk/image/2.jpg",file); } }
如此,高清大圖就從桌面上愉快的轉移到了騰訊雲上啦!
關注微信公眾號, 隨時隨地學習


