java對象存儲工具類
package top.yuechenc.xingchen.common.utils;
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.*;
import com.qcloud.cos.region.Region;
import com.tencent.cloud.CosStsClient;
import lombok.Data;
import org.json.JSONObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
/**
* @description: 騰訊對象存儲服務
* @author: Zhiwei Wang
* @create: 2020/12/30
*/
@Data
@Component
@PropertySource("other.yml")
@ConfigurationProperties(prefix = "tencent")
public class CosClientTest implements InitializingBean {
/**
* 騰訊雲的SecretId
*/
@Value("${secretId}")
private String secretId;
/**
* 騰訊雲的SecretKey
*/
@Value("${secretKey}")
private String secretKey;
/**
* 騰訊雲的bucket (存儲桶)
*/
@Value("${bucket}")
private String bucket;
/**
* 騰訊雲的region(bucket所在地區)
*/
@Value("${region}")
private String region;
/**
* 騰訊雲的allowPrefix(允許上傳的路徑)
*/
@Value("${allowPrefix}")
private String allowPrefix;
/**
* 騰訊雲的臨時密鑰時長(機關秒)
*/
@Value("${durationSeconds}")
private String durationSeconds;
/**
* 騰訊雲的通路基礎連結
*/
@Value("${baseUrl}")
private String baseUrl;
@Override
public void afterPropertiesSet() {
System.out.println("================="+secretId);
}
/**
* @param fullFileName 檔案伺服器下的根路徑,即key,如: doc/picture.jpg
* @param file
* @return 成功傳回檔案路徑, 失敗傳回null
* @description: 使用臨時秘鑰上傳檔案
* @author: Zhiwei Wang
* @date: 2020/12/30 9:36
*/
public String keyUploadFile(String fullFileName, 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, fullFileName, 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 + fullFileName;
} catch (CosServiceException e) {
//失敗,抛出 CosServiceException
e.printStackTrace();
} catch (CosClientException e) {
//失敗,抛出 CosClientException
e.printStackTrace();
} finally {
// 關閉用戶端
cosclient.shutdown();
//傳回檔案的網絡通路url
return rtValue;
}
}
private void keyDownloadFile() {
//擷取臨時密鑰
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);
}
/**
* 生成臨時密鑰
*
* @return
*/
private 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 !");
}
}
/**
* 初始化CosClient相關配置, appid、accessKey、secretKey、region
*
* @return
*/
public COSClient getCosClient() {
// 1 初始化使用者身份資訊(secretId, secretKey)。
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 設定 bucket 的區域, COS 地域的簡稱請參照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了設定 region, https(預設 http), 逾時, 代理等 set 方法, 使用可參見源碼或者常見問題 Java SDK 部分。
Region regiona = new Region(region);
ClientConfig clientConfig = new ClientConfig(regiona);
// 3 生成 cos 用戶端。
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
/**
* 上傳檔案
*
* @return
*/
public String uploadFile(String fullFileName, File file) {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fullFileName, file);
// 設定存儲類型, 預設是标準(Standard), 低頻(standard_ia)
putObjectRequest.setStorageClass(StorageClass.Standard_IA);
COSClient cc = getCosClient();
String etag = "";
String resutl;
try {
PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
// putobjectResult會傳回檔案的etag
etag = putObjectResult.getETag();
resutl = baseUrl + fullFileName;
} catch (CosServiceException e) {
e.printStackTrace();
resutl=e.getMessage();
} catch (CosClientException e) {
e.printStackTrace();
resutl=e.getMessage();
}finally {
// 關閉用戶端
cc.shutdown();
}
return resutl;
}
/**
* 下載下傳檔案
*
* @param bucketName
* @param path
* @return
*/
public String downLoadFile(String bucketName, String path, String fullFileName) {
File downFile = new File(fullFileName);
COSClient cc = getCosClient();
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
ObjectMetadata downObjectMeta = cc.getObject(getObjectRequest, downFile);
cc.shutdown();
String etag = downObjectMeta.getETag();
return etag;
}
/**
* 删除檔案
*
* @param bucketName
* @param path
*/
public void deleteFile(String bucketName, String path) {
COSClient cc = getCosClient();
try {
cc.deleteObject(bucketName, path);
} catch (CosClientException e) {
e.printStackTrace();
} finally {
cc.shutdown();
}
}
/**
* 建立桶
*
* @param bucketName
* @return
* @throws CosClientException
* @throws CosServiceException
*/
public Bucket createBucket(String bucketName) throws CosClientException, CosServiceException {
COSClient cc = getCosClient();
Bucket bucket = null;
try {
bucket = cc.createBucket(bucketName);
} catch (CosClientException e) {
e.printStackTrace();
} finally {
}
return bucket;
}
;
/**
* 删除桶
*
* @param bucketName
* @throws CosClientException
* @throws CosServiceException
*/
public void deleteBucket(String bucketName) throws CosClientException, CosServiceException {
COSClient cc = getCosClient();
try {
cc.deleteBucket(bucketName);
} catch (CosClientException e) {
e.printStackTrace();
} finally {
}
}
;
/**
* 判斷桶是否存在
*
* @param bucketName
* @return
* @throws CosClientException
* @throws CosServiceException
*/
public boolean doesBucketExist(String bucketName) throws CosClientException, CosServiceException {
COSClient cc = getCosClient();
boolean bucketExistFlag = cc.doesBucketExist(bucketName);
return bucketExistFlag;
}
;
/**
* 檢視桶檔案
*
* @param bucketName
* @return
* @throws CosClientException
* @throws CosServiceException
*/
public ObjectListing listObjects(String bucketName) throws CosClientException, CosServiceException {
COSClient cc = getCosClient();
// 擷取 bucket 下成員(設定 delimiter)
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
listObjectsRequest.setBucketName(bucketName);
// 設定 list 的 prefix, 表示 list 出來的檔案 key 都是以這個 prefix 開始
listObjectsRequest.setPrefix("");
// 設定 delimiter 為/, 即擷取的是直接成員,不包含目錄下的遞歸子成員
listObjectsRequest.setDelimiter("/");
// 設定 marker, (marker 由上一次 list 擷取到, 或者第一次 list marker 為空)
listObjectsRequest.setMarker("");
// 設定最多 list 100 個成員,(如果不設定, 預設為 1000 個,最大允許一次 list 1000 個 key)
listObjectsRequest.setMaxKeys(100);
ObjectListing objectListing = cc.listObjects(listObjectsRequest);
// 擷取下次 list 的 marker
String nextMarker = objectListing.getNextMarker();
// 判斷是否已經 list 完, 如果 list 結束, 則 isTruncated 為 false, 否則為 true
boolean isTruncated = objectListing.isTruncated();
List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
for (COSObjectSummary cosObjectSummary : objectSummaries) {
// get file path
String key = cosObjectSummary.getKey();
// get file length
long fileSize = cosObjectSummary.getSize();
// get file etag
String eTag = cosObjectSummary.getETag();
// get last modify time
Date lastModified = cosObjectSummary.getLastModified();
// get file save type
String StorageClassStr = cosObjectSummary.getStorageClass();
}
return objectListing;
}
public void main(String[] args) {
//uploadFile();
//downLoadFile();
//deleteFile();
//createBucket();
//deleteBucket();
//doesBucketExist();
//listObjects();
}
}
springboot配置檔案
tencent:
# 騰訊雲的SecretId(永久的,可在控制台開啟或關閉)
secretId: ***
# 騰訊雲的SecretKey(永久的,可在控制台開啟或關閉)
secretKey: ***
# 騰訊雲的allowPrefix(允許上傳的路徑)
allowPrefix: '*'
# 騰訊雲的通路基礎連結:
baseUrl: https://xingchen-***.cos.ap-chengdu.myqcloud.com/
# 騰訊雲的bucket (存儲桶)
bucket: xingchen-***
# 騰訊雲的臨時密鑰時長(機關秒)
durationSeconds: 1800
# 騰訊雲的region(bucket所在地區)
region: ap-chengdu