public override Task <StorageUploadParameters> RequestUpload(RequestUploadOptions options)
        {
            var headers = new Dictionary <string, string>();

            if (options.Length > 0)
            {
                headers.Add("Content-Length", options.Length.ToString());
            }

            var url = cos.GenerateSignURL(new COSXML.Model.Tag.PreSignatureStruct
            {
                isHttps    = true,
                httpMethod = "PUT",
                appid      = cosConfig.Appid,
                bucket     = this.bucket,
                region     = cosConfig.Region,
                headers    = headers,
                key        = options.DestFilePath,
            });

            return(Task.FromResult(new StorageUploadParameters
            {
                Url = url,
                Method = "PUT"
            }));
        }
        /// 获取预签名下载链接
        public void GetPresignDownloadUrl()
        {
            //.cssg-snippet-body-start:[get-presign-download-url]
            try
            {
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                preSignatureStruct.appid              = "1250000000";               //腾讯云账号 APPID
                preSignatureStruct.region             = "COS_REGION";               //存储桶地域
                preSignatureStruct.bucket             = "examplebucket-1250000000"; //存储桶
                preSignatureStruct.key                = "exampleobject";            //对象键
                preSignatureStruct.httpMethod         = "GET";                      //HTTP 请求方法
                preSignatureStruct.isHttps            = true;                       //生成 HTTPS 请求 URL
                preSignatureStruct.signDurationSecond = 600;                        //请求签名时间为600s
                preSignatureStruct.headers            = null;                       //签名中需要校验的 header
                preSignatureStruct.queryParameters    = null;                       //签名中需要校验的 URL 中请求参数

                string requestSignURL = cosXml.GenerateSignURL(preSignatureStruct);

                //下载请求预签名 URL (使用永久密钥方式计算的签名 URL)
                string           localDir      = System.IO.Path.GetTempPath(); //本地文件夹
                string           localFileName = "my-local-temp-file";         //指定本地保存的文件名
                GetObjectRequest request       = new GetObjectRequest(null, null, localDir, localFileName);
                //设置下载请求预签名 URL
                request.RequestURLWithSign = requestSignURL;
                //设置进度回调
                request.SetCosProgressCallback(delegate(long completed, long total)
                {
                    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                });
                //执行请求
                GetObjectResult result = cosXml.GetObject(request);
                //请求成功
                Console.WriteLine(result.GetResultInfo());
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }

            //.cssg-snippet-body-end
        }
Example #3
0
        public void Download(string name)
        {
            try
            {
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct
                {
                    appid              = _cosSettings.AppId,                                // 腾讯云账号 APPID
                    region             = _cosSettings.Region,                               // 存储桶地域
                    bucket             = $"{_cosSettings.BucketName}-{_cosSettings.AppId}", // 存储桶
                    key                = name,                                              // 对象键
                    httpMethod         = "GET",                                             // HTTP 请求方法
                    isHttps            = true,                                              // 生成 HTTPS 请求 URL
                    signDurationSecond = 600,                                               // 请求签名时间为600s
                    headers            = null,                                              // 签名中需要校验的 header
                    queryParameters    = null                                               // 签名中需要校验的 URL 中请求参数
                };

                string requestSignUrl = _cosXml.GenerateSignURL(preSignatureStruct);

                //下载请求预签名 URL (使用永久密钥方式计算的签名 URL)
                //string localDir = System.IO.Path.GetTempPath();//本地文件夹
                //string localFileName = "my-local-temp-file"; //指定本地保存的文件名
                //GetObjectRequest request = new GetObjectRequest(null, null, localDir, localFileName);
                ////设置下载请求预签名 URL
                //request.RequestURLWithSign = requestSignURL;
                ////设置进度回调
                //request.SetCosProgressCallback(delegate (long completed, long total)
                //{
                //    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                //});
                ////执行请求
                //GetObjectResult result = cosXml.GetObject(request);
                ////请求成功
                //Console.WriteLine(result.GetResultInfo());
                Console.WriteLine(requestSignUrl);
            }
            catch (CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
        }
        private async Task <string> PresignedObjectAsync(string bucketName, string objectName, int expiresInt, PresignedObjectType type)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            if (string.IsNullOrEmpty(objectName))
            {
                throw new ArgumentNullException(nameof(objectName));
            }
            if (expiresInt <= 0)
            {
                throw new Exception("ExpiresIn time can not less than 0.");
            }
            if (expiresInt > 7 * 24 * 3600)
            {
                throw new Exception("ExpiresIn time no more than 7 days.");
            }
            long               nowTime            = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            const int          minExpiresInt      = 600;
            string             key                = Encrypt.MD5($"{bucketName}_{objectName}_{type.ToString().ToUpper()}");
            string             objectUrl          = null;
            string             newBucketName      = ConvertBucketName(bucketName);
            PreSignatureStruct preSignatureStruct = new PreSignatureStruct()
            {
                appid              = Options.Endpoint,
                region             = Options.Region,
                bucket             = newBucketName,
                key                = objectName,
                httpMethod         = type.ToString().ToUpper(),
                isHttps            = Options.IsEnableHttps,
                signDurationSecond = expiresInt,
                headers            = null,
                queryParameters    = null,
            };

            //查找缓存
            if (Options.IsEnableCache && (expiresInt > minExpiresInt))
            {
                var cacheResult = await _cache.GetAsync <PresignedUrlCache>(key);

                PresignedUrlCache cache = cacheResult.HasValue ? cacheResult.Value : null;
                //缓存中存在,且有效时间不低于10分钟
                if (cache != null &&
                    cache.Type == type &&
                    cache.CreateTime > 0 &&
                    (cache.CreateTime + expiresInt - nowTime) > minExpiresInt &&
                    cache.Name == objectName &&
                    cache.BucketName == bucketName)
                {
                    return(cache.Url);
                }
            }
            if (type == PresignedObjectType.Get)
            {
                //生成URL
                AccessMode accessMode = await this.GetObjectAclAsync(bucketName, objectName);

                if (accessMode == AccessMode.PublicRead || accessMode == AccessMode.PublicReadWrite)
                {
                    objectUrl = $"{(Options.IsEnableHttps ? "https" : "http")}://{newBucketName}.cos.{Options.Region}.myqcloud.com{(objectName.StartsWith("/") ? "" : "/")}{objectName}";
                }
                else
                {
                    string uri = _client.GenerateSignURL(preSignatureStruct);
                    if (uri != null)
                    {
                        objectUrl = uri.ToString();
                    }
                }
            }
            else
            {
                string uri = _client.GenerateSignURL(preSignatureStruct);
                if (uri != null)
                {
                    objectUrl = uri.ToString();
                }
            }
            if (string.IsNullOrEmpty(objectUrl))
            {
                throw new Exception("Presigned get object url failed.");
            }
            //save cache
            if (Options.IsEnableCache && expiresInt > minExpiresInt)
            {
                PresignedUrlCache urlCache = new PresignedUrlCache()
                {
                    Url        = objectUrl,
                    CreateTime = nowTime,
                    Name       = objectName,
                    BucketName = bucketName,
                    Type       = type
                };
                int randomSec = new Random().Next(5, 30);
                await _cache.SetAsync(key, urlCache, TimeSpan.FromSeconds(expiresInt + randomSec));
            }
            return(objectUrl);
        }