Unity 接入腾讯云COS对象存储
网上没找到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是储存空间,上传浏览下载需要额外购买下行流量包,提醒一下,避免欠费...