將文件上傳到騰訊云對象存儲(COS,Cloud Object Storage)可以通過騰訊云提供的 SDK 實現。以下是詳細的步驟和示例代碼,幫助您完成文件上傳操作。
步驟
-
注冊騰訊云賬號并創建存儲桶:
(1)登錄騰訊云控制臺,進入?對象存儲 COS。(2)創建一個存儲桶(Bucket),并獲取存儲桶的名稱和所屬地域(Region)。 -
獲取 API 密鑰:
在騰訊云控制臺的?訪問管理?中,獲取您的?SecretId
?和?SecretKey
。 -
添加騰訊云 COS SDK 依賴:
在項目中引入騰訊云 COS 的 Java SDK。 -
編寫 Java 代碼上傳文件:
使用 SDK 提供的 API 上傳文件到騰訊云 COS。
依賴庫
在 Maven 項目pom.xml添加以下依賴:
<dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>5.6.89</version>
</dependency>
示例代碼
以下是一個完整的 Java 示例代碼,演示如何將本地文件上傳到騰訊云 COS:
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.region.Region;
import lombok.extern.slf4j.Slf4j;/*** 騰訊cos文件上傳工具類**/
@Slf4j
public class TencentCOSUtil {//創建鏈接public static COSClient getCOSClient() {try {// 1. 初始化用戶身份信息(SecretId 和 SecretKey)String accessKey = "your accessKey";String secretKey = "your secretKey";COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);// 2. 設置存儲桶的地域Region region = new Region("ap-guangzhou");ClientConfig clientConfig = new ClientConfig(region);// 創建COClient實例。return new COSClient(cred, clientConfig);} catch (Exception e) {throw new BusinessException("創建騰訊云OSS連接失敗");}}}
? 上傳文件
/*** 上傳文件。** @param inputStream 以流的方式上傳文件* @param path 上傳的文件存放路徑* @param fileName 指定的文件名* @param suffix 上傳的文件后綴* @return 文件在服務器上的全路徑*/public static String upLoad(InputStream inputStream, String path, String fileName, String suffix, boolean signFlag) {if (inputStream == null) {return null;}String bucketName = "your bucketName";String endpoint = "your endpoint";String fileUrl = null;// 文件名格式SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.PURE_DATETIME_PATTERN);String newFileName = null;if (StrUtil.isNotBlank(fileName)) {newFileName = fileName + RandomUtil.randomString(5) + "." + suffix;} else {newFileName = sdf.format(new Date()) + RandomUtil.randomString(5) + "." + suffix;}String filePath = path + "/" + newFileName;fileUrl = endpoint + "/" + filePath;COSClient cosClient = getCOSClient();try {// 創建上傳Object的MetadataObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setCacheControl("no-cache");objectMetadata.setHeader("Pragma", "no-cache");// 上傳文件PutObjectResult putResult = cosClient.putObject(bucketName, filePath, inputStream, objectMetadata);if (putResult != null) {fileUrl = signFlag ? generatePresignedUrl(cosClient, fileUrl) : fileUrl;}} catch (CosClientException oe) {log.error(oe.getMessage());throw oe;} finally {cosClient.shutdown();}log.info("[cosUpLoad]文件全路徑fileUrl={}", fileUrl);return fileUrl;}
文件簽名及設置過期時間
public static String generatePresignedUrl(COSClient cosClient, String fileUrl) {String bucketName="your bucketName";if (StrUtil.isBlankIfStr(fileUrl)) {return fileUrl;}if (cosClient == null) {cosClient = getCOSClient();}// 設置URL過期時間Date expiration = DateUtil.offsetMinute(new Date(), 3);try {String filePath = new URL(fileUrl).getPath().substring(1);filePath = URLDecoder.decode(filePath, "UTF-8");// 生成以GET方法訪問的簽名URL,訪客可以直接通過瀏覽器訪問相關內容。URL url = cosClient.generatePresignedUrl(bucketName, filePath, expiration);return url.toString();} catch (CosClientException ce) {log.error("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with COS, "+ "such as not being able to access the network.");log.error("Error Message:" + ce.getMessage());} catch (MalformedURLException e) {log.error("[cosSignedUrl]文件地址格式有誤", e);} catch (UnsupportedEncodingException e) {log.error("[cosSignedUrl]中文文件地址轉換異常", e);} finally {if (cosClient != null) {cosClient.shutdown();}}return null;}
調用上傳方法上傳文件
public static void main(String[] args) {//從數據庫查詢業務數據List<UserData> projectList = new ArrayList<>();ByteArrayOutputStream out = new ByteArrayOutputStream();EasyExcel.write(out, UserData.class).sheet(0).doWrite(projectList);String fileUrl = null;try {fileUrl = TencentCOSUtil.upLoad(new ByteArrayInputStream(out.toByteArray()),"userData" + "/" + DateUtil.format(new Date(), "yyyy-MM"),"用戶信息","xlsx", true);} catch (Exception e) {log.error("[userData]導出失敗:", e);} finally {if (out != null) {try {out.close();} catch (IOException e) {log.error("[userData]關閉流失敗", e);}}}if (fileUrl != null) {log.info("導出成功,文件fileUrl={}",fileUrl);}log.info("導出失敗,文件fileUrl={}",fileUrl);}
代碼說明
-
初始化身份信息:
使用?SecretId
?和?SecretKey
?創建?COSCredentials
?對象。 -
設置存儲桶地域:
根據存儲桶的地域(如?ap-beijing
)創建?ClientConfig
?對象。 -
創建 COSClient:
使用?COSCredentials
?和?ClientConfig
?創建?COSClient
?實例。 -
上傳文件:
指定存儲桶名稱、本地文件路徑和文件在 COS 上的存儲路徑(Key)。使用?PutObjectRequest
?創建上傳請求,并調用?cosClient.putObject()
?方法上傳文件。 -
關閉 COSClient:
上傳完成后,調用?cosClient.shutdown()
?關閉客戶端。
關鍵參數
-
SecretId 和 SecretKey:騰訊云 API 密鑰,用于身份驗證。
-
BucketName:存儲桶名稱,格式為?
<BucketName-APPID>
,例如?examplebucket-1250000000
。 -
Region:存儲桶所在地域,例如?
ap-beijing
(北京)。 -
Key:文件在 COS 上的存儲路徑,例如?
uploads/file.txt
。
注意事項
-
權限設置:
(1)確保存儲桶的權限設置為允許上傳。(2)如果需要公開訪問,可以設置文件的訪問權限為公共讀。 -
文件大小限制:
單個文件上傳最大支持 5 TB。如果文件較大,建議使用分塊上傳(SDK 也支持分塊上傳 API)。 -
安全性:
不要將?SecretId
?和?SecretKey
?硬編碼在代碼中,建議使用環境變量或配置文件管理。