Ejemplo n.º 1
0
        /// 上传时图片处理
        public void UploadWithPicOperation()
        {
            string bucket  = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
            string key     = "exampleobject";            //对象键
            string srcPath = @"temp-source-file";        //本地文件绝对路径
            //.cssg-snippet-body-start:[upload-with-pic-operation]
            PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);

            JObject o = new JObject();

            // 不返回原图
            o["is_pic_info"] = 0;
            JArray  rules = new JArray();
            JObject rule  = new JObject();

            rule["bucket"] = bucket;
            rule["fileid"] = "desample_photo.jpg";
            //处理参数,规则参见:https://cloud.tencent.com/document/product/460/19017
            rule["rule"] = "imageMogr2/thumbnail/400x400";
            rules.Add(rule);
            o["rules"] = rules;

            string ruleString = o.ToString(Formatting.None);

            request.SetRequestHeader("Pic-Operations", ruleString);
            //执行请求
            PutObjectResult result = cosXml.PutObject(request);
            //.cssg-snippet-body-end
        }
Ejemplo n.º 2
0
        public Task PutAsync(string remotename, Stream stream, CancellationToken cancelToken)
        {
            try
            {
                cosXml = GetCosXml();
                string bucket = _cosOptions.Bucket;
                string key    = GetFullKey(remotename);

                byte[] buffer = new byte[stream.Length];
                if (Utility.Utility.ForceStreamRead(stream, buffer, buffer.Length) != stream.Length)
                {
                    throw new Exception("Bad file read");
                }

                PutObjectRequest request = new PutObjectRequest(bucket, key, buffer);

                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), KEY_DURATION_SECOND);
                request.SetRequestHeader("Content-Type", "application/octet-stream");

                PutObjectResult result = cosXml.PutObject(request);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                Logging.Log.WriteErrorMessage(LOGTAG, "PutAsync", clientEx, "Put failed: {0}", remotename);
                throw;
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                Logging.Log.WriteErrorMessage(LOGTAG, "PutAsync", serverEx, "Put failed: {0}, {1}", remotename, serverEx.GetInfo());
                throw;
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
        /// 简单上传对象
        public void PutObject()
        {
            //.cssg-snippet-body-start:[put-object]
            try
            {
                string bucket  = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
                string key     = "exampleobject";            //对象键
                string srcPath = @"temp-source-file";        //本地文件绝对路径

                PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);
                //设置进度回调
                request.SetCosProgressCallback(delegate(long completed, long total)
                {
                    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                });
                //执行请求
                PutObjectResult result = cosXml.PutObject(request);
                //对象的 eTag
                string eTag = result.eTag;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }

            //.cssg-snippet-body-end
        }
Ejemplo n.º 4
0
        public string Upload(byte[] data, string fileName)
        {
            // 上传对象
            try
            {
                var bucket           = $"{_cosSettings.BucketName}-{_cosSettings.AppId}"; //存储桶,格式:BucketName-APPID
                var cosPath          = fileName;                                          // 对象键
                var putObjectRequest = new PutObjectRequest(bucket, cosPath, data);

                _cosXml.PutObject(putObjectRequest);

                return($"https://{bucket}.cos.{_cosSettings.Region}.myqcloud.com/{cosPath}");
            }
            catch (CosClientException clientEx)
            {
                //请求失败
                _logger.LogError("CosClientException: " + clientEx);
                throw;
            }
            catch (CosServerException serverEx)
            {
                //请求失败
                _logger.LogError("CosServerException: " + serverEx.GetInfo());
                throw;
            }
        }
Ejemplo n.º 5
0
        /// 上传时进行二维码识别
        public void UploadWithQRcodeRecognition()
        {
            string bucket  = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
            string key     = "exampleobject";            //对象键
            string srcPath = @"temp-source-file";        //本地文件绝对路径
            //.cssg-snippet-body-start:[upload-with-QRcode-recognition]
            PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);

            JObject o = new JObject();

            // 不返回原图
            o["is_pic_info"] = 1;
            JArray  rules = new JArray();
            JObject rule  = new JObject();

            rule["bucket"] = bucket;
            rule["fileid"] = "qrcode.jpg";
            //处理参数,规则参见:https://cloud.tencent.com/document/product/460/37513
            rule["rule"] = "QRcode/cover/<mode>";
            rules.Add(rule);
            o["rules"] = rules;

            string ruleString = o.ToString(Formatting.None);

            request.SetRequestHeader("Pic-Operations", ruleString);
            //执行请求
            PutObjectResult result = cosXml.PutObject(request);
            //.cssg-snippet-body-end
        }
        /// 高级接口上传二进制数据
        public void TransferUploadBytes()
        {
            //.cssg-snippet-body-start:[transfer-upload-bytes]
            try
            {
                string           bucket           = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
                string           cosPath          = "exampleObject";            // 对象键
                byte[]           data             = new byte[1024];             // 二进制数据
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, data);

                cosXml.PutObject(putObjectRequest);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
            //.cssg-snippet-body-end
        }
Ejemplo n.º 7
0
        /// 获取预签名上传链接
        public void GetPresignUploadUrl()
        {
            //.cssg-snippet-body-start:[get-presign-upload-url]
            try
            {
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                preSignatureStruct.appid              = "1250000000";               //腾讯云账号 APPID
                preSignatureStruct.region             = "COS_REGION";               //存储桶地域
                preSignatureStruct.bucket             = "examplebucket-1250000000"; //存储桶
                preSignatureStruct.key                = "exampleobject";            //对象键
                preSignatureStruct.httpMethod         = "PUT";                      //HTTP 请求方法
                preSignatureStruct.isHttps            = true;                       //生成 HTTPS 请求 URL
                preSignatureStruct.signDurationSecond = 600;                        //请求签名时间为 600s
                preSignatureStruct.headers            = null;                       //签名中需要校验的 header
                preSignatureStruct.queryParameters    = null;                       //签名中需要校验的 URL 中请求参数

                //上传预签名 URL (使用永久密钥方式计算的签名 URL)
                string requestSignURL = cosXml.GenerateSignURL(preSignatureStruct);

                string           srcPath = @"temp-source-file";//本地文件绝地路径
                PutObjectRequest request = new PutObjectRequest(null, null, srcPath);
                //设置上传请求预签名 URL
                request.RequestURLWithSign = requestSignURL;
                //设置进度回调
                request.SetCosProgressCallback(delegate(long completed, long total)
                {
                    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                });
                //执行请求
                PutObjectResult result = cosXml.PutObject(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
        }
Ejemplo n.º 8
0
        public bool TransferUploadBytes(string cosPath, byte[] data, string filename = "", bool isAttachment = false)
        {
            //.cssg-snippet-body-start:[transfer-upload-bytes]
            try
            {
                PutObjectRequest putObjectRequest = new PutObjectRequest(options.Bucket, cosPath, data);

                if (!string.IsNullOrWhiteSpace(filename))
                {
                    putObjectRequest.SetRequestHeader("Content-Disposition", $"{(isAttachment ? "attachment" : "inline")}; filename={System.Web.HttpUtility.UrlEncode(filename)}");
                }

                var r = cosXml.PutObject(putObjectRequest);

                if (r.IsSuccessful())
                {
                    return(true);
                }

                logger.LogError(r.httpMessage);
                return(false);

                //throw new BadRequestException(WFw.Results.OperationResultType.IsErr, r.httpMessage);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                logger.LogError(clientEx, $"CosClientException");

                return(false);
                // throw new BadRequestException(WFw.Results.OperationResultType.IsErr, clientEx.ToString());
                //请求失败
                //Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                logger.LogError(serverEx, $"TransferUploadBytes");
                //请求失败
                //Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                //throw new BadRequestException(WFw.Results.OperationResultType.IsErr, serverEx.GetInfo());
                return(false);
            }
        }
        public async Task <bool> PutObjectAsync(string bucketName, string objectName, string filePath, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            if (string.IsNullOrEmpty(objectName))
            {
                throw new ArgumentNullException(nameof(objectName));
            }
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }
            if (!File.Exists(filePath))
            {
                throw new Exception("Upload file is not exist.");
            }
            bucketName = ConvertBucketName(bucketName);
            PutObjectRequest request = new PutObjectRequest(bucketName, objectName, filePath);
            PutObjectResult  result  = _client.PutObject(request);

            return(await Task.FromResult(result.IsSuccessful()));
        }