Esempio n. 1
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <returns>Oss文件地址</returns>
        private async Task <string> PutObject(Stream stream, string key, string mimeType)
        {
            var bucketInfo     = BucketInfo.CreateByRegion(CommConstant.OssRegion, CommConstant.OssBucket);
            var requestContent = new RequestContent
            {
                ContentType   = RequestContentType.Stream,
                StreamContent = stream,
                MimeType      = mimeType
            };

            var result = await _client.PutObjectAsync(bucketInfo, key, requestContent);

            if (!result.IsSuccess)
            {
                var message = string.Format("ErrorMessage:{0}", result.ErrorMessage);
                if (result.ErrorResult != null)
                {
                    message += string.Format("{0}HostId:{1}{2}RequestId:{3}{4}Code:{5}{6}Message:{7}{8}", Environment.NewLine,
                                             result.ErrorResult.HostId, Environment.NewLine,
                                             result.ErrorResult.RequestId, Environment.NewLine,
                                             result.ErrorResult.Code, Environment.NewLine,
                                             result.ErrorResult.Message, Environment.NewLine
                                             );
                }
                //LogHelper.WriteError(message, result.InnerException);
                return(string.Empty);
            }
            return(key);
        }
Esempio n. 2
0
        public override ServiceRequest BuildRequest()
        {
            var req = new ServiceRequest(BucketInfo.CreateByRegion(_region, ""), "", HttpMethod.Get);

            req.AddParameter(RequestParameters.PREFIX, _request.Prefix);
            req.AddParameter(RequestParameters.MARKER, _request.Marker);
            req.AddParameter(RequestParameters.MAX_KEYS, _request.MaxKeys?.ToString());

            return(req);
        }
Esempio n. 3
0
    public static async Task Main(string[] args)
    {
        if (args.Length < 2)
        {
            Console.WriteLine("Please run with bucket name and file path");
            return;
        }

        var bucketName = args[0];
        var filePath   = args[1];

        var conf = new ConfigurationBuilder()
                   .SetBasePath(Directory.GetCurrentDirectory())
                   .AddJsonFile("appsettings.json", true, true)
                   .AddJsonFile("appsettings.Development.json", true, true)
                   .Build();

        IServiceCollection services = new ServiceCollection();

        services.AddOssClient(conf);
        var sp     = services.BuildServiceProvider();
        var client = sp.GetService <OssClient>();

        var bucket         = BucketInfo.CreateByRegion(OssRegions.HangZhou, bucketName, false, false);
        var remoteFilePaht = $"test/{DateTime.Now.ToString("yyyyMMddHHmmss")}.png";

        using (var fs = new FileStream(filePath, FileMode.Open))
        {
            var file = new RequestContent()
            {
                MimeType      = "images/png",
                ContentType   = RequestContentType.Stream,
                StreamContent = fs,
            };

            var result = await client.PutObjectAsync(bucket, remoteFilePaht, file);

            if (result.IsSuccess)
            {
                Console.WriteLine("Succeeded!");
            }
            else
            {
                Console.WriteLine("Failed!");
                Console.WriteLine(result.ErrorMessage);
            }
        }
    }
        internal static string Region = OssRegions.ShangHai; //设置要操作的区域



        public static async Task RunAsync()
        {
            var crediential = new OssCredential()
            {
                AccessKeyId     = AccessKeyId,
                AccessKeySecret = AssessSecret
            };

            var client = new OssClient(crediential);

            ////list buckets
            //var listBucketResult = await client.ListBucketsAsync(OssRegions.ShangHai);
            //Console.WriteLine(listBucketResult.IsSuccess + ":" + listBucketResult.ErrorMessage);

            var bucket = BucketInfo.CreateByRegion(Region, BucketName, false, false);

            // put string
            {
                string content   = "这是一个文本文件\naaaaaaaa\nbbbbbb\nccccccccc";
                var    putResult = await client.PutObjectAsync(bucket, "test_put_object_string.txt", content);

                Console.WriteLine($"Put string object  {putResult.IsSuccess} {putResult.ErrorMessage}  Etag:{putResult.SuccessResult?.ETag}");
            }



            // put file
            {
                var file      = @"D:\Work\Weixin\resource\IMG_1399.png";
                var putResult = await client.PutObjectByFileNameAsync(bucket, "test_put_file.png", file);

                Console.WriteLine($"Put file object  {putResult.IsSuccess} {putResult.ErrorMessage}  Etag:{putResult.SuccessResult?.ETag}");
            }

            //// copy file
            //Console.WriteLine("\n\n===Copy Object=============");
            //var copyResult =
            //    await
            //        client.CopyObjectAsync(bucket, "test_put_object_string.txt", bucket,
            //            "test_03_copy_object_string.txt", null);
            //Console.WriteLine($"Copy object  {copyResult.IsSuccess} {copyResult.ErrorMessage}  Etag:{copyResult.SuccessResult?.LastModified}");

            //// get file
            //Console.WriteLine("\n\n===Get Object=============");
            //var getResult = await client.GetObjectAsync(bucket, "test_put_object_string.txt");
            //Console.WriteLine($"Get Object = {getResult.IsSuccess}");
            //if (getResult.IsSuccess)
            //{
            //    var content = await getResult.SuccessResult.Content.ReadAsStringAsync();
            //    Console.WriteLine("FileContent" + content);
            //}

            //// append file
            //Console.WriteLine("\n\n===append Object=============");
            //{
            //    var content = "This is a line 这是一行字符串.";
            //    var file = new OssObjectInfo()
            //    {
            //        ContentType = RequestContentType.String,
            //        MimeType = "text/text",
            //        StringContent = content
            //    };
            //    var appendResult = await client.AppendObject(bucket, "test_append_object.txt", 0, file);
            //    Console.WriteLine($"1st append:{appendResult.IsSuccess} nextPos={appendResult.SuccessResult?.NextAppendPosition}");
            //    if (appendResult.IsSuccess)
            //    {
            //        appendResult = await client.AppendObject(bucket, "test_append_object.txt", appendResult.SuccessResult.NextAppendPosition, file);
            //        Console.WriteLine($"2st append:{appendResult.IsSuccess} nextPos={appendResult.SuccessResult?.NextAppendPosition}");

            //    }
            //}

            //// delete object
            //Console.WriteLine("\n\n===append Object=============");
            //{
            //    var content = "This is a line 这是一行字符串.";
            //    var key = "test_delete_object.txt";
            //    var putResult = await client.PutObjectAsync(bucket, key, content);
            //    if (putResult.IsSuccess)
            //    {
            //        var deleteResult = await client.DeleteObjectAsync(bucket, key);
            //        Console.WriteLine($"Delete reuslt:{deleteResult.IsSuccess} {deleteResult.ErrorMessage}");
            //    }
            //    else
            //    {
            //        Console.WriteLine($" Put object failed.{putResult.ErrorMessage}");
            //    }
            //}

            //// delete multiple
            //Console.WriteLine("\n\n===delete multiple=============");
            //{
            //    var content = "This is a line 这是一行字符串.";

            //    IList<string> fielKeys = new List<string>();

            //    for (int i = 1; i < 10; i++)
            //    {
            //        var key = $"test_delete_multi_object_{i}.txt";
            //        var putResult = await client.PutObjectAsync(bucket, key, content);
            //        if (putResult.IsSuccess == false)
            //        {
            //            Console.WriteLine($" Put object {i} failed.{putResult.ErrorMessage}");
            //            return;
            //        }
            //        fielKeys.Add(key);
            //    }

            //    var deleteResult = await client.DeleteMultipleObjectsAsync(bucket, fielKeys, false);

            //    Console.WriteLine($"Delete multi:{deleteResult.IsSuccess} {deleteResult.ErrorMessage}");

            //}


            // head object
            // delete multiple
            Console.WriteLine("\n\n===head object=============");
            {
                var content = "This is a line 这是一行字符串.";
                var key     = "test_head_object.txt";
                //var putResult = await client.PutObjectAsync(bucket, key, content);
                //if (putResult.IsSuccess)
                {
                    var headResult = await client.HeadObjectAsync(bucket, key, null);

                    Console.WriteLine($"Head object: {headResult.IsSuccess} {headResult.ErrorMessage}");
                }
            }


            Console.WriteLine("\n\n===Get object meta=============");
            {
                //var content = "This is a line 这是一行字符串.";
                var key = "test_get_meta_object.txt";
                //var putResult = await client.PutObjectAsync(bucket, key, content);
                //if (putResult.IsSuccess)
                {
                    var headResult = await client.GetObjectMetaAsync(bucket, key);

                    Console.WriteLine($"Head object: {headResult.IsSuccess} {headResult.ErrorMessage}");
                }
            }
        }