首页 > 编程语言 > 详细

Unity 接入腾讯云COS对象存储

时间:2020-03-02 17:13:20      阅读:301      评论:0      收藏:0      [点我收藏+]

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

Unity 接入腾讯云COS对象存储

原文:https://www.cnblogs.com/Mr147/p/12396164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!