Esempio n. 1
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);
        }
        /// 设置自定义头部
        public void SetCustomHeaders()
        {
            string bucket  = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
            string key     = "exampleobject";            //对象键
            string srcPath = @"temp-source-file";        //本地文件绝对路径
            //.cssg-snippet-body-start:[set-custom-headers]
            PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);

            request.SetRequestHeader("x-cos-meta-key", "value");
            request.SetRequestHeader("Content-Disposition", "attachment");

            COSXMLUploadTask uploadTask = new COSXMLUploadTask(request);

            uploadTask.SetSrcPath(srcPath);
            //.cssg-snippet-body-end
        }
        /// 上传时图片处理
        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
        }
        /// 上传时添加盲水印
        public void PutObjectWithWatermark()
        {
            string bucket  = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID
            string key     = "exampleobject";            //对象键
            string srcPath = @"temp-source-file";        //本地文件绝对路径
            //.cssg-snippet-body-start:[put-object-with-watermark]
            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"] = key;
            //处理参数,规则参见:https://cloud.tencent.com/document/product/460/19017
            rule["rule"] = "watermark/3/type/<type>/image/<imageUrl>/text/<text>/level/<level>";
            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 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
        }
Esempio n. 6
0
        public void PutObjectWithDeSample()
        {
            string key     = "original_photo.jpg";
            string srcPath = localTempPhotoFilePath;

            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"] = "desample_photo.jpg";
            //处理参数,规则参见:https://cloud.tencent.com/document/product/460/19017
            rule["rule"] = "imageMogr2/thumbnail/400x";
            rules.Add(rule);
            o["rules"] = rules;
            string ruleString = o.ToString(Formatting.None);

            request.SetRequestHeader("Pic-Operations", ruleString);
            //执行请求
            PutObjectResult result       = QCloudServer.Instance().cosXml.PutObject(request);
            var             uploadResult = result.uploadResult;

            // Console.WriteLine(result.GetResultInfo());
            Assert.IsNotEmpty((result.GetResultInfo()));

            Assert.True(result.IsSuccessful());
            Assert.NotNull(uploadResult);

            Assert.NotNull(uploadResult.originalInfo);
            Assert.NotNull(uploadResult.originalInfo.ETag);
            Assert.NotNull(uploadResult.originalInfo.Key);
            Assert.NotNull(uploadResult.originalInfo.Location);
            Assert.NotNull(uploadResult.originalInfo.imageInfo.Ave);
            Assert.NotNull(uploadResult.originalInfo.imageInfo.Format);
            Assert.NotNull(uploadResult.originalInfo.imageInfo.Orientation);
            Assert.NotZero(uploadResult.originalInfo.imageInfo.Width);
            Assert.NotZero(uploadResult.originalInfo.imageInfo.Height);
            Assert.NotZero(uploadResult.originalInfo.imageInfo.Quality);

            Assert.NotNull(uploadResult.processResults);
            Assert.NotZero(uploadResult.processResults.results.Count);
            Assert.True(uploadResult.processResults.results[0].Width <= 400);
            Assert.True(uploadResult.processResults.results[0].Height <= 400);
            Assert.NotNull(uploadResult.processResults.results[0].ETag);
            Assert.NotNull(uploadResult.processResults.results[0].Format);
            Assert.NotNull(uploadResult.processResults.results[0].Key);
            Assert.NotNull(uploadResult.processResults.results[0].Location);
            Assert.NotZero(uploadResult.processResults.results[0].Quality);
            Assert.NotZero(uploadResult.processResults.results[0].Size);
            Assert.Zero(uploadResult.processResults.results[0].WatermarkStatus);
        }
Esempio n. 7
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);
            }
        }
Esempio n. 8
0
        public void testUploadTask()
        {
            string key = multiKey;

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

            request.SetRequestHeader("Content-Type", "image/png");

            COSXMLUploadTask uploadTask = new COSXMLUploadTask(request);

            uploadTask.SetSrcPath(bigFileSrcPath);

            var    autoEvent = new AutoResetEvent(false);
            string eTag      = null;

            uploadTask.progressCallback = delegate(long completed, long total)
            {
                Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
            };
            uploadTask.successCallback = delegate(CosResult cosResult)
            {
                COSXML.Transfer.COSXMLUploadTask.UploadTaskResult result = cosResult as COSXML.Transfer.COSXMLUploadTask.UploadTaskResult;
                Console.WriteLine(result.GetResultInfo());
                autoEvent.Set();
                eTag = result.eTag;
            };
            uploadTask.failCallback = delegate(CosClientException clientEx, CosServerException serverEx)
            {
                if (clientEx != null)
                {
                    Console.WriteLine("CosClientException: " + clientEx);
                }
                if (serverEx != null)
                {
                    Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                }
                autoEvent.Set();
            };
            transferManager.Upload(uploadTask);
            autoEvent.WaitOne();
            Assert.NotNull(eTag);
        }
Esempio n. 9
0
        public override IVirgoFile Upload(string fileName, long fileLength, Stream data, string group = null, string subdir = null, string extra = null, string fileContentType = null)
        {
            FileAttachment file = new FileAttachment
            {
                FileName   = fileName,
                Length     = fileLength,
                UploadTime = DateTime.Now,
                SaveMode   = SaveFileModeEnum.TenCos.ToString(),
                ExtraInfo  = extra
            };
            var ext = string.Empty;

            if (string.IsNullOrEmpty(fileName) == false)
            {
                var dotPos = fileName.LastIndexOf('.');
                ext = fileName.Substring(dotPos + 1);
            }
            file.FileExt = ext;

            var ossSettings = _config.FileUploadOptions.Settings.Where(x => x.Key.ToLower() == "tencos").Select(x => x.Value).FirstOrDefault();
            FileHandlerOptions groupInfo = null;

            if (string.IsNullOrEmpty(group))
            {
                groupInfo = ossSettings?.FirstOrDefault();
            }
            else
            {
                groupInfo = ossSettings?.Where(x => x.GroupName.ToLower() == group.ToLower()).FirstOrDefault();
                if (groupInfo == null)
                {
                    groupInfo = ossSettings?.FirstOrDefault();
                }
            }
            if (groupInfo == null)
            {
                return(null);
            }


            string pathHeader = "";

            if (string.IsNullOrEmpty(subdir) == false)
            {
                pathHeader = Path.Combine(pathHeader, subdir);
            }
            else
            {
                var sub = VirgoFileProvider._subDirFunc?.Invoke(this);
                if (string.IsNullOrEmpty(sub) == false)
                {
                    pathHeader = Path.Combine(pathHeader, sub);
                }
            }
            //var fullPath = Path.Combine(pathHeader, $"{Guid.NewGuid():N}.{file.FileExt}");
            //fullPath = fullPath.Replace("\\", "/");

            BinaryReader binaryReader = new BinaryReader(data);
            var          fs           = binaryReader.ReadBytes((int)fileLength);


            CosXmlConfig config = new CosXmlConfig.Builder()
                                  .SetConnectionTimeoutMs(60000) //设置连接超时时间,单位毫秒,默认45000ms
                                  .SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位毫秒,默认45000ms
                                  .IsHttps(false)                //设置默认 HTTPS 请求
                                  .SetAppid(groupInfo.AppId)     //设置腾讯云账户的账户标识 APPID
                                  .SetRegion(groupInfo.GroupName)
                                  .Build();
            long durationSecond = 600;          //每次请求签名有效时长,单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(groupInfo.Secret,
                                                                                                    groupInfo.Key, durationSecond);
            CosXml           cosXml  = new CosXmlServer(config, qCloudCredentialProvider);
            string           bucket  = groupInfo.GroupLocation + "-" + groupInfo.AppId;                  //存储桶,格式:BucketName-APPID
            string           key     = Guid.NewGuid().ToString("N") + "." + file.FileName.Split(".")[1]; //对象在存储桶中的位置,即称对象键
            PutObjectRequest request = new PutObjectRequest(bucket, key, fs);

            request.SetRequestHeader("Content-Type", fileContentType);
            //设置签名有效时长
            request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.Seconds), 600);
            //设置进度回调
            //request.SetCosProgressCallback(delegate (long completed, long total)
            //{
            //    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
            //});
            //执行请求
            PutObjectResult result = cosXml.PutObject(request);

            if (result.httpCode == 200)
            {
                file.Path      = "http://" + bucket + ".cos." + groupInfo.GroupName + ".myqcloud.com" + request.RequestPath;
                file.ExtraInfo = groupInfo.GroupName;
                file.FileName  = key;
                _dc.AddEntity(file);
                _dc.SaveChanges();
                return(file);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 10
0
        public void QRCodeRecognition()
        {
            string key = qrPhotoKey;
            // 下载云上有内容的 QR Code
            string           srcPath    = localQRCodeTempPhotoFilePath;
            GetObjectRequest getRequest = new GetObjectRequest(bucket, key, ".", localQRCodeTempPhotoFilePath);
            GetObjectResult  getResult  = QCloudServer.Instance().cosXml.GetObject(getRequest);

            Assert.True(200 == getResult.httpCode);

            // 开始请求上传时 QR code 识别
            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/0";
            rules.Add(rule);
            o["rules"] = rules;

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

            request.SetRequestHeader("Pic-Operations", ruleString);
            //执行请求
            PutObjectResult result       = QCloudServer.Instance().cosXml.PutObject(request);
            var             uploadResult = result.uploadResult;

            Assert.IsNotEmpty((result.GetResultInfo()));
            Assert.True(result.IsSuccessful());
            Assert.NotNull(uploadResult);

            Assert.NotNull(uploadResult.originalInfo);
            Assert.NotNull(uploadResult.originalInfo.ETag);
            Assert.NotNull(uploadResult.originalInfo.Key);
            Assert.NotNull(uploadResult.originalInfo.Location);
            Assert.NotNull(uploadResult.originalInfo.imageInfo.Format);
            Assert.NotZero(uploadResult.originalInfo.imageInfo.Width);
            Assert.NotZero(uploadResult.originalInfo.imageInfo.Height);
            Assert.NotZero(uploadResult.originalInfo.imageInfo.Quality);

            Assert.NotNull(uploadResult.processResults);
            Assert.NotZero(uploadResult.processResults.results.Count);
            Assert.NotNull(uploadResult.processResults.results[0].ETag);
            Assert.NotNull(uploadResult.processResults.results[0].Format);
            Assert.NotNull(uploadResult.processResults.results[0].Key);
            Assert.NotNull(uploadResult.processResults.results[0].Location);
            Assert.NotZero(uploadResult.processResults.results[0].Quality);
            Assert.NotZero(uploadResult.processResults.results[0].Size);
            Assert.AreEqual(uploadResult.processResults.results[0].CodeStatus, 1);
            Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo);
            Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo.CodeUrl);
            Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo.CodeLocation);
            Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo.CodeLocation.Point);
            Assert.True(uploadResult.processResults.results[0].QRcodeInfo.CodeLocation.Point.Count > 0);

            QRCodeRecognitionRequest rRequest = new QRCodeRecognitionRequest(bucket, key, 0);

            QRCodeRecognitionResult rResult = QCloudServer.Instance().cosXml.QRCodeRecognition(rRequest);

            Assert.IsNotEmpty((rResult.GetResultInfo()));
            Assert.True(rResult.IsSuccessful());
            Assert.NotNull(rResult.recognitionResult);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo);
            Assert.Null(rResult.recognitionResult.ResultImage);
            Assert.AreEqual(rResult.recognitionResult.CodeStatus, 1);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeUrl);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point);
            Assert.True(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point.Count > 0);

            // with cover
            rRequest = new QRCodeRecognitionRequest(bucket, key, 1);

            rResult = QCloudServer.Instance().cosXml.QRCodeRecognition(rRequest);

            Assert.IsNotEmpty((rResult.GetResultInfo()));
            Assert.True(rResult.IsSuccessful());
            Assert.NotNull(rResult.recognitionResult);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo);
            Assert.NotNull(rResult.recognitionResult.ResultImage);
            Assert.AreEqual(rResult.recognitionResult.CodeStatus, 1);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeUrl);
            Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point);
            Assert.True(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point.Count > 0);
        }