網上沒找到COS對應.net新版本的教程,就踩完記錄下來
首先注冊騰訊雲巴拉巴拉,下載.net sdk巴拉巴拉
放到Unity項目中,刪掉不必要的測試模塊,剩下的如下圖
然后建立一個測試腳本,代碼如下
using UnityEngine; using COSXML; using COSXML.Auth; using COSXML.Model.Object; using System.IO; using COSXML.Utils; using System; public class COSTest : MonoBehaviour { public string appid = "";//設置騰訊雲賬戶的賬戶標識 APPID public string bucket = "";//存儲桶,格式:BucketName-APPID public string key = "exampleobject";//對象在存儲桶中的位置,即稱對象鍵 public string secretId = ""; //雲 API 密鑰 SecretId public string secretKey = ""; //雲 API 密鑰 SecretKey public string region = "ap-guangzhou"; // Start is called before the first frame update void Start() { Upload(); } public void Upload() { CosXmlConfig config = new CosXmlConfig.Builder() .SetConnectionTimeoutMs(60000) //設置連接超時時間,單位毫秒,默認45000ms .SetReadWriteTimeoutMs(40000) //設置讀寫超時時間,單位毫秒,默認45000ms .IsHttps(true) //設置默認 HTTPS 請求 .SetAppid(appid) .SetRegion(region) .Build(); long durationSecond = 600; //每次請求簽名有效時長,單位為秒 QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider); try { string srcPath = @"temp-source-file";//本地文件絕對路徑 if (!File.Exists(srcPath)) { // 如果不存在目標文件,創建一個臨時的測試文件 File.WriteAllBytes(srcPath, new byte[1024]); } PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath); //設置簽名有效時長 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //設置進度回調 request.SetCosProgressCallback(delegate (long completed, long total) { Debug.Log(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //執行請求 PutObjectResult result = cosXml.PutObject(request); //對象的 eTag string eTag = result.eTag; } catch (COSXML.CosException.CosClientException clientEx) { //請求失敗 Debug.Log("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //請求失敗 Debug.Log("CosServerException: " + serverEx.GetInfo()); } } }
一個簡單的上傳測試,填入自己的AppID,secretId,secretKey,bucket,region等參數
Github地址:https://github.com/busiyg/QCloudUnityDemo
騰訊雲送的半年每月50G是儲存空間,上傳瀏覽下載需要額外購買下行流量包,提醒一下,避免欠費...