/// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="accessKeyId"></param>
        /// <param name="accessKeySecret"></param>
        /// <param name="bucketName"></param>
        /// <param name="key"></param>
        /// <param name="fileExt">文件扩展名称</param>
        /// <param name="fileStream"></param>
        /// <returns>文件名称</returns>
        public static bool UploadFile(string endpoint, string accessKeyId, string accessKeySecret, string bucketName, string key, string fileExt, Stream fileStream)
        {
            var result = true;

            try
            {
                fileExt = fileExt.TrimStart('.').ToLower();
                var contentType = GetContentType(fileExt);
                var metadata    = new ObjectMetadata();
                if (!string.IsNullOrEmpty(contentType))
                {
                    metadata.ContentType = contentType;
                }

                //
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                //var
                client.PutObject(bucketName, key, fileStream, metadata);
                //
            }
            catch (Exception ex)
            {
                result = false;
            }

            return(result);
        }
Beispiel #2
0
        public void UploadFile(OssClient client, Stream stream)
        {
            TkDebug.AssertArgumentNull(client, "client", this);
            TkDebug.AssertArgumentNull(stream, "stream", this);

            client.PutObject(BucketName, ObjectName, stream);
        }
Beispiel #3
0
        public Uri GenerateUri(OssClient client)
        {
            TkDebug.AssertArgumentNull(client, "client", this);

            return(client.GeneratePresignedUri(BucketName, ObjectName,
                                               DateTime.Now + AliyunOSSSetting.Current.UrlCacheTime));
        }
Beispiel #4
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="accessKeyId">开发者秘钥对,通过阿里云控制台的秘钥管理页面创建与管理</param>
        /// <param name="accessKeySecret">开发者秘钥对,通过阿里云控制台的秘钥管理页面创建与管理</param>
        /// <param name="endpoint">Endpoint,创建Bucket时对应的Endpoint</param>
        /// <param name="bucketName">Bucket名称,创建Bucket时对应的Bucket名称</param>
        /// <param name="key">文件标识</param>
        /// <param name="file">下载存放的文件路径</param>
        public static void GetObject(string accessKeyId, string accessKeySecret, string endpoint, string bucketName, string key, string file)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var result = client.GetObject(bucketName, key);
                using (var requestStream = result.Content)
                {
                    using (var fs = File.Open(file, FileMode.OpenOrCreate))
                    {
                        int length = 4 * 1024;
                        var buf    = new byte[length];
                        do
                        {
                            length = requestStream.Read(buf, 0, length);
                            fs.Write(buf, 0, length);
                        } while (length != 0);
                    }
                }
            }
            catch (OssException ex)
            {
            }
        }
Beispiel #5
0
        public ValueTask <bool> Delete(FileObject fileObject)
        {
            bool result = true;
            var  key    = fileObject.FileInfo.FullPath;

            if (key.IsNull())
            {
                result = false;
            }

            // 创建OssClient实例。
            var client = new OssClient(_config.Endpoint, _config.AccessKeyId, _config.AccessKeySecret);

            try
            {
                // 删除文件
                client.DeleteObject(_config.BucketName, key);

                result = true;
            }
            catch (Exception ex)
            {
                _logger.LogError("阿里云OSS文件删除异常:{@ex}", ex);
            }
            return(new ValueTask <bool>(result));
        }
        public static void PutStreamBySignedUrl(string bucketName, string key)
        {
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                // Step1: Genereates url signature
                var generatePresignedUriRequest = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Put);
                var signedUrl = client.GeneratePresignedUri(generatePresignedUriRequest);

                // Step2: Prepares for stream to be uploaded and sends out this request.
                var buffer = Encoding.UTF8.GetBytes("Aliyun OSS SDK for C#");
                using (var ms = new MemoryStream(buffer))
                {
                    client.PutObject(signedUrl, ms);
                }

                Console.WriteLine("Get object by signatrue succeeded.");
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                  ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        public static void SetRootDomains()
        {
            const string accessId = "<your access id>";
            const string accessKey = "<your access key>";
            const string endpoint = "<valid host name>";

            try
            {
                var conf = new ClientConfiguration();
                var domainList = conf.RootDomainList;
                foreach (var domain in domainList)
                {
                    Console.WriteLine(domain);
                }

                Console.WriteLine("\nafter modifed: ");
                var domains = new List<string> {".alibaba-inc.com", ".aliyuncs.gd"};
                conf.RootDomainList = domains;
                foreach (string domain in conf.RootDomainList)
                {
                    Console.WriteLine(domain);
                }

                var client = new OssClient(new Uri(endpoint), accessId, accessKey, conf);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        ///  <summary>
        /// 删除图片 货号表
        /// </summary>
        public bool DeleteAllPicByScode()
        {
            bool flag = false;
            int  n    = -1;

            try
            {
                OssClient client = new OssClient(endpoint, accessId, accessKey);

                string   Ids   = Request.QueryString["arryId"];
                string   scode = Request.QueryString["scode"];
                string   src   = "";
                string[] arryId;
                arryId = Ids.Split(',');
                foreach (var item in arryId)
                {
                    string delsql = @"update scodepic set Def4='2',Def1='1',Def2='1',Def3='1',UserId='" + userInfo.User.Id + "' where Id='" + item + "' ";
                    src = DbHelperSQL.Query(@"select * from scodepic where Id='" + item + "'").Tables[0].Rows[0]["scodePicSrc"].ToString();
                    DbHelperSQL.ExecuteSql(@"update stylepic set Def4='2',Def1='1',Def2='1',Def3='1',UserId='" + userInfo.User.Id + "' where stylePicSrc='" + src + "' ");
                    n = DbHelperSQL.ExecuteSql(delsql);
                    client.DeleteObject(bucketName, src.Replace(@"http://best-bms.pbxluxury.com/", ""));
                }
                if (n != -1)
                {
                    flag = true;
                }
            }
            catch
            {
                flag = false;
            }
            return(flag);
        }
Beispiel #9
0
 public OssObjectSet()
 {
     if (this.Client == null)
     {
         Client = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);
     }
 }
Beispiel #10
0
        //public AliyunOssService(AliyunOssConfig config)
        //{
        //  this._ossConfig = config;
        //}
        /// <summary>
        /// 上传文件获取访问Key
        /// </summary>
        /// <param name="name"></param>
        /// <param name="path"></param>
        /// <param name="fileStream"></param>
        /// <returns></returns>
        public string UploadImgReturnKey(string name, string path, MemoryStream fileStream)
        {
            var ossClient = new OssClient(_ossConfig.EndPoint, _ossConfig.AccessKey, _ossConfig.AccessSecret);
            var result    = ossClient.PutObject(_ossConfig.Bucket, name, fileStream);

            return(result.RequestId);
        }
Beispiel #11
0
        public FileOssClient(FileOssConfig config)
        {
            string endpoint        = config.Endpoint;
            string accessKeyId     = config.AccessKeyId;
            string accessKeySecret = config.AccessKeySecret;

            client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            bucketName = config.BucketName;

            try
            {
                bool isCreateBucket = true;
                foreach (Bucket bucket in client.ListBuckets())
                {
                    if (bucket != null && bucketName.Equals(bucket.Name))
                    {
                        isCreateBucket = false;
                        break;
                    }
                }
                //if (client.ListBuckets().Where(p => p.Equals(bucketName)).First() == null)
                if (isCreateBucket)
                {
                    client.CreateBucket(bucketName);
                }
            } catch (Exception ex)
            {
                Console.WriteLine("exMsg:" + ex.Message);
            }
        }
Beispiel #12
0
        public static void DeleteObjects()
        {
            const string accessKeyId     = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint        = "<valid host name>";

            const string bucketName = "<your bucket name>";

            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var keys       = new List <string>();
                var listResult = client.ListObjects(bucketName);
                foreach (var summary in listResult.ObjectSummaries)
                {
                    Console.WriteLine(summary.Key);
                    keys.Add(summary.Key);
                }
                var request = new DeleteObjectsRequest(bucketName, keys, false);
                client.DeleteObjects(request);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                  ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        //查看相册中有哪些相片(名称、时间、以及存储空间),可用于用户来查看相片数和相片名称
        public void ListObjects()
        {
            int count  = 0;
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var listObjectsRequest = new ListObjectsRequest("igets");
                var result             = client.ListObjects(listObjectsRequest);
                Console.WriteLine("成功检索出这些文件:");
                foreach (var summary in result.ObjectSummaries)
                {
                    count++;
                    Console.WriteLine(summary.Key);
                    //summary.Key是文件名
                    //summary.LastModified是文件上传时间
                    //summary.BucketName是存储空间名字(相当于相册名)
                }
                Console.WriteLine(count + "张相片");//显示此相册中相片数目有多少
            }
            catch (Exception ex)
            {
                Console.WriteLine("List object failed, {0}", ex.Message);
            }
        }
        //
        public static void GetBucketLifecycle()
        {
            var client = new OssClient("oss-cn-shenzhen.aliyuncs.com", "LTAId7dsrQHujhU5", "O3nQOqai4yXrvGCKNbvgrKuU8f7U7p");

            try
            {
                var rules = client.GetBucketLifecycle("igets");

                Console.WriteLine("Get bucket:{0} Lifecycle succeeded ", "igets");

                foreach (var rule in rules)
                {
                    Console.WriteLine("ID: {0}", rule.ID);
                    Console.WriteLine("Prefix: {0}", rule.Prefix);
                    Console.WriteLine("Status: {0}", rule.Status);
                    if (rule.ExpriationDays.HasValue)
                    {
                        Console.WriteLine("ExpirationDays: {0}", rule.ExpriationDays);
                    }
                    if (rule.ExpirationTime.HasValue)
                    {
                        Console.WriteLine("ExpirationTime: {0}", FormatIso8601Date(rule.ExpirationTime.Value));
                    }
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                  ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Beispiel #15
0
        public static List <string> GetFileUrls(string endpoint, string bucketName, string accessKeyId, string accessKeySecret, string folder = null)
        {
            List <string> urls = new List <string>();

            try
            {
                ObjectListing result     = null;
                string        nextMarker = string.IsNullOrEmpty(folder) ? "" : folder;

                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                do
                {
                    var listObjectsRequest = new ListObjectsRequest(bucketName)
                    {
                        MaxKeys = 1000,
                        Marker  = nextMarker,
                    };
                    result = client.ListObjects(listObjectsRequest);
                    foreach (var summary in result.ObjectSummaries)
                    {
                        if (!string.IsNullOrEmpty(folder) && summary.Key.StartsWith(folder))
                        {
                            urls.Add(summary.Key);
                        }
                    }
                    nextMarker = result.NextMarker;
                } while (result.IsTruncated);
            }
            catch (Exception e)
            {
            }
            return(urls);
        }
Beispiel #16
0
 //图片上传
 public void PutTexure2DWithStr(UploadMan uploadMan)
 {
     try
     {
         client = new OssClient(AddressConfig.EndPoint, uploadMan.accessKeyId, uploadMan.accessKeySecret, uploadMan.securityToken);
         byte[] data = uploadMan.texData;
         using (Stream stream = new MemoryStream(data))
         {
             if (client != null)
             {
                 //Bucket名称.Endpoint / Object名称
                 client.PutObject(uploadMan.bucket, uploadMan.lineid + "/" + uploadMan.fileName, stream);
                 Debug.Log("图片上传成功:" + uploadMan.fileName);
                 string url = string.Format("https://{0}.{1}/{2}", uploadMan.bucket, AddressConfig.EndPoint, uploadMan.lineid + "/" + uploadMan.fileName);
                 Debug.LogFormat("url:" + url);
                 uploadMan.Method?.Invoke(uploadMan.fileName);
             }
         }
     }
     catch (OssException e)
     {
         Debug.Log("图片上传错误:" + e);
     }
     catch (System.Exception e)
     {
         Debug.Log("图片上传错误:" + e);
     }
 }
        public static void PutLocalFileBySignedUrl(string bucketName, string key)
        {
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                // Step1: Genereates url signature
                var request = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Put);
                request.Expiration = DateTime.Now.AddMinutes(5);

                var signedUrl = client.GeneratePresignedUri(request);

                // Step2: Prepares for filepath to be uploaded and sends out this request.
                client.PutObject(signedUrl, fileToUpload);

                Console.WriteLine("Put object by signatrue succeeded.");
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                  ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Beispiel #18
0
        public static void GetFileFromOSS(string accesskey, string secret, string endpoint, string bucketname, string objName, string filename)
        {
            var client = new OssClient(endpoint, accesskey, secret);

            try
            {
                var getObjectRequest = new GetObjectRequest(bucketname, objName);
                var fs = File.Open(filename, FileMode.OpenOrCreate);
                getObjectRequest.StreamTransferProgress += streamProgressCallback;
                var ossObject = client.GetObject(getObjectRequest);
                using (var stream = ossObject.Content)
                {
                    var buffer    = new byte[1024 * 1024];
                    var bytesRead = 0;
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, bytesRead);
                        // 处理读取的数据(此处代码省略)。
                    }
                    fs.Close();
                }
                Console.WriteLine($"Download File:{filename} succeeded");
            }
            catch (OssException ex)
            {
                Console.WriteLine($"Failed with error code: {ex.ErrorCode}; Error info: {ex.Message}. \nRequestID:{ex.RequestId}\tHostID:{ex.HostId}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed with error info: { ex.Message}");
            }
        }
Beispiel #19
0
        public void GetVersionFromAbsentAttributes()
        {
            DocumentPackage package   = CreateDefaultDocumentPackage();
            OssClient       ossClient = CreateDefaultOssClient();

            Assert.AreEqual(false, ossClient.IsSdkVersionSetInPackageData(package));
        }
        public static void DeleteObjects()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<your bucket name>";

            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var keys = new List<string>();
                var listResult = client.ListObjects(bucketName);
                foreach (var summary in listResult.ObjectSummaries)
                {
                    Console.WriteLine(summary.Key);
                    keys.Add(summary.Key);
                }
                var request = new DeleteObjectsRequest(bucketName, keys, false);
                client.DeleteObjects(request);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        public static void GetObjectPartly()
        {
            const string localFilePath   = "<your localFilePath>";
            const string bucketName      = "<your bucketName>";
            const string fileKey         = "<your fileKey>";
            const string accessKeyId     = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint        = "<your endpoint>";

            _client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            using (var fileStream = new FileStream(localFilePath, FileMode.OpenOrCreate))
            {
                var       bufferedStream = new BufferedStream(fileStream);
                var       objectMetadata = _client.GetObjectMetadata(bucketName, fileKey);
                var       fileLength     = objectMetadata.ContentLength;
                const int partSize       = 1024 * 1024 * 10;

                var partCount = CalPartCount(fileLength, partSize);

                for (var i = 0; i < partCount; i++)
                {
                    var startPos = partSize * i;
                    var endPos   = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1;
                    Download(bufferedStream, startPos, endPos, localFilePath, bucketName, fileKey);
                }
                bufferedStream.Flush();
            }
        }
        public static void SetBucketAcl()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<bucket name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                client.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                //client.SetBucketAcl(new SetBucketAclRequest(bucketName, CannedAccessControlList.PublicRead));
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        public static void GetObjectPartly()
        {
            const string localFilePath = "<your localFilePath>";
            const string bucketName = "<your bucketName>";
            const string fileKey = "<your fileKey>";
            const string accessId = "<your access id>";
            const string  accessKey = "<your access key>";

            _client = new OssClient(accessId, accessKey);

            using (var fileStream = new FileStream(localFilePath, FileMode.OpenOrCreate))
            {
                var bufferedStream = new BufferedStream(fileStream);
                var objectMetadata = _client.GetObjectMetadata(bucketName, fileKey);
                var fileLength = objectMetadata.ContentLength;
                const int partSize = 1024 * 1024 * 10;

                var partCount = CalPartCount(fileLength, partSize);

                for (var i = 0; i < partCount; i++)
                {
                    var startPos = partSize * i;
                    var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1;
                    Download(bufferedStream, startPos, endPos, localFilePath, bucketName, fileKey);
                }
                bufferedStream.Flush();
            }
        }
		private void button1_Click(object sender, EventArgs e)
		{
			var dlg = new OpenFileDialog();
			dlg.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif";
			dlg.Multiselect = true;
			dlg.ShowDialog();

			if (dlg.FileName.Length <= 0)
				return;

			var oss = new OssClient(EndPoint, AccessKeyId, AccessKeySecret);

			foreach (var fileName in dlg.FileNames)
			{
				using (var file = new FileStream(fileName, FileMode.Open))
				{
					var meta = new ObjectMetadata();
					meta.ContentLength = file.Length;

					var destName = "avatar/" + Path.GetFileName(fileName);

					var result = oss.PutObject(BucketName, destName, file, meta);
					textBox1.AppendText(string.Format("Uploaded : {0}, {1}\n", destName, result.ETag));
				}
			}
		}
        //下载文件(相当于客户下载相片,可多图下载)
        public void GetObject1()
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                string[] names = new string[] { "banner.jpg", "pics.jpg" };//根据用户选择图片的多少来自定义

                //将从OSS读取到的文件写到本地并循环文件集
                for (int i = 0; i < names.Length; i++)
                {
                    var obj = client.GetObject("igets", names[i]);
                    using (var requestStream = obj.Content)
                    {
                        byte[] buf = new byte[1024];
                        using (var fs = File.Open("E:/Content/" + names[i] + "", FileMode.OpenOrCreate))//此处,必须要加name(作为下载文件的名字),否则会显示“对路径的存储错误”
                        {
                            var len = 0;
                            while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                            {
                                fs.Write(buf, 0, len);
                            }
                        }
                    }
                }

                Console.WriteLine("成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Beispiel #26
0
        public static void DeleteObjects()
        {
            var client = new OssClient(Endpoint, AccessId, AccessKey);

            try
            {
                var keys = new List<string>();
                var listResult = client.ListObjects(BucketName);
                foreach (var summary in listResult.ObjectSummaries)
                {
                    Console.WriteLine(summary.Key);
                    keys.Add(summary.Key);
                }
                var request = new DeleteObjectsRequest(BucketName, keys, false);
                client.DeleteObjects(request);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Beispiel #27
0
 protected void btnCreateBucket_Click(object sender, EventArgs e)
 {
     OssClient ossClient = new OssClient(endpoint, accessId, accessKey);
     try
     {
         ossClient.CreateBucket(bucketName);
         Console.WriteLine("创建成功!Bucket: " + bucketName);
     }
     catch (OssException ex)
     {
         if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
         {
             // 这里示例处理一种特定的ErrorCode。
             Console.WriteLine(string.Format("Bucket '{0}' 已经存在,请更改名称后再创建。", bucketName));
         }
         else
         {
             // RequestID和HostID可以在有问题时用于联系客服诊断异常。
             Console.WriteLine(string.Format("创建失败。错误代码:{0}; 错误消息:{1}。\nRequestID:{2}\tHostID:{3}",
                 ex.ErrorCode,
                 ex.Message,
                 ex.RequestId,
                 ex.HostId));
         }
     }
 }
        public static void UploadFile(string localServerPath,string folerPath,string fileName,string extType,byte[] file)
        {
            string localOrigineImageDirectory = localServerPath + folerPath;
            string localThumbDirectory = localServerPath + folerPath + "thumb/";
            if (!Directory.Exists(localOrigineImageDirectory))
                Directory.CreateDirectory(localOrigineImageDirectory);
            if (!Directory.Exists(localThumbDirectory))
                Directory.CreateDirectory(localThumbDirectory);
            
            // 原图存储在本地
            var fs = new FileStream(localOrigineImageDirectory + fileName + "." + extType, FileMode.Create, FileAccess.Write);
            fs.Write(file, 0, file.Length);
            fs.Flush();
            fs.Close();


            OssClient ossClient = new OssClient("http://oss-cn-beijing.aliyuncs.com", ConfigurationManager.AppSettings["ossId"], ConfigurationManager.AppSettings["ossKey"]);
            ObjectMetadata metadata=new ObjectMetadata();
            metadata.ContentType = extType=="jpg"?"image/jpeg":"";
            PutObjectResult result = ossClient.PutObject("baolinks",folerPath+fileName + "." + extType, new MemoryStream(file),metadata);
           

            //// 1000-751缩略图:立刻生成并写入本地
            //var oss1= ossClient.GetObject(new GetObjectRequest("baolinks", folerPath+fileName + "." + extType+"@!1000-751"));
            //WriteLocalFile(localThumbDirectory + fileName + "_1000_751" + "." + extType,StreamToBytes(oss1.Content));

            //// 350-215 缩略图:立刻生成并写入本地
            //var oss2 = ossClient.GetObject(new GetObjectRequest("baolinks", folerPath + fileName + "." + extType + "@!350-215"));
            //WriteLocalFile(localThumbDirectory + fileName + "_350_215" + "." + extType, StreamToBytes(oss2.Content));

            //// 90-90 缩略图:立刻生成并写入本地
            //var oss3 = ossClient.GetObject(new GetObjectRequest("baolinks", folerPath + fileName + "." + extType + "@!90-90"));
            //WriteLocalFile(localThumbDirectory + fileName + "_90_90" + "." + extType, StreamToBytes(oss3.Content));

        }
Beispiel #29
0
        public static void UploadFile(string localPath, string buckName, string key)
        {
            bool waitForResult = true;

            if (!File.Exists(localPath))
            {
                Debug.LogError("File path not exist: " + localPath);
            }

            using (var fs = File.Open(localPath, FileMode.Open))
            {
                OssClient ossClient = new OssClient(Config.Endpoint, Config.AccessKeyId, Config.AccessKeySecret);
                try
                {
                    var metadata = new ObjectMetadata();
                    metadata.ContentLength = fs.Length;
                    metadata.CacheControl  = "public";

                    ossClient.BeginPutObject(buckName, key, fs, metadata, (asyncResult) =>
                    {
                        try
                        {
                            ossClient.EndPutObject(asyncResult);
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError(ex);
                        }
                        finally
                        {
                            if (OnUploaded != null)
                            {
                                OnUploaded.Invoke();
                            }
                            waitForResult = false;
                        }
                    }, null);
                }
                catch (OssException ex)
                {
                    Debug.LogError(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                                 ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
                    waitForResult = false;
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex);
                    waitForResult = false;
                }

                while (waitForResult)
                {
                    if (OnUploading != null)
                    {
                        OnUploading.Invoke();
                    }
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// 拷贝大文件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="sourceBucket">源空间</param>
        /// <param name="sourceKey">源文件</param>
        /// <param name="optBucket">目标空间</param>
        /// <param name="optKey">目标文件</param>
        /// <returns></returns>
        private CopyFileResultDto CopyBigFile(OssClient client, string sourceBucket, string sourceKey,
                                              string optBucket, string optKey)
        {
            var initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(optBucket, optKey);
            var result = client.InitiateMultipartUpload(initiateMultipartUploadRequest);

            var partSize  = Core.Tools.GetPartSize(ChunkUnit.U4096K);
            var metadata  = client.GetObjectMetadata(sourceBucket, sourceKey);
            var fileSize  = metadata.ContentLength;
            var partCount = (int)fileSize / partSize;

            if (fileSize % partSize != 0)
            {
                partCount++;
            }

            // 开始分片拷贝。
            var partETags = new List <PartETag>();

            for (var i = 0; i < partCount; i++)
            {
                var skipBytes = (long)partSize * i;
                var size      = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
                // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。
                var uploadPartCopyRequest =
                    new UploadPartCopyRequest(optBucket, optKey, sourceBucket, sourceKey,
                                              result.UploadId)
                {
                    PartSize   = size,
                    PartNumber = i + 1,
                    // BeginIndex用来定位此次上传分片开始所对应的位置。
                    BeginIndex = skipBytes
                };
                // 调用uploadPartCopy方法来拷贝每一个分片。
                var uploadPartCopyResult = client.UploadPartCopy(uploadPartCopyRequest);
                Console.WriteLine("UploadPartCopy : {0}", i);
                partETags.Add(uploadPartCopyResult.PartETag);
            }

            // 完成分片拷贝。
            var completeMultipartUploadRequest =
                new CompleteMultipartUploadRequest(optBucket, optKey, result.UploadId);

            // partETags为分片上传中保存的partETag的列表,OSS收到用户提交的此列表后,会逐一验证每个数据分片的有效性。全部验证通过后,OSS会将这些分片合成一个完整的文件。
            foreach (var partETag in partETags)
            {
                completeMultipartUploadRequest.PartETags.Add(partETag);
            }

            var ret = client.CompleteMultipartUpload(completeMultipartUploadRequest);

            if (ret.HttpStatusCode == HttpStatusCode.OK)
            {
                return(new CopyFileResultDto(true, sourceKey, "success"));
            }

            return(new CopyFileResultDto(false, sourceKey,
                                         $"RequestId:{ret.RequestId},HttpStatusCode:{ret.HttpStatusCode}"));
        }
        /// <summary>
        /// 获取文件长度
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public long GetFileLength(string name)
        {
            OssClient client         = new OssClient(m_endPoint, m_keyID, m_keySecret);
            var       objectMetadata = client.GetObjectMetadata(m_bucket, name);
            var       fileLength     = objectMetadata.ContentLength;

            return(fileLength);
        }
Beispiel #32
0
 public static OssClient GetInstance(string accessId, string accessKey, string endPoint)
 {
     if (ossClient == null)
     {
         ossClient = new OssClient(endPoint, accessId, accessKey);
     }
     return(ossClient);
 }
Beispiel #33
0
        public string GetFilePath(string objectname, DateTime expirationTime)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            var uri    = client.GeneratePresignedUri(bucketName, objectname, expirationTime);
            var url    = uri.AbsoluteUri;

            return(url);
        }
Beispiel #34
0
 public static OssClient GetInstance()
 {
     if (ossClient == null)
     {
         ossClient = new OssClient(Global.OssHttp, Global.AccessId, Global.AccessKey);
     }
     return(ossClient);
 }
Beispiel #35
0
 static FileHelper()
 {
     accessKeyId     = ConfigHelper.GetValue("accessKeyId");
     accessKeySecret = ConfigHelper.GetValue("accessKeySecret");
     endpoint        = ConfigHelper.GetValue("endpoint");
     bucketName      = ConfigHelper.GetValue("bucketName");
     client          = new OssClient(endpoint, accessKeyId, accessKeySecret);
 }
 public AliyunOSSService(OssClient client
                         , IEasyCachingProvider provider
                         , OSSOptions options)
 {
     this._client = client ?? throw new ArgumentNullException(nameof(OssClient));
     this._cache  = provider ?? throw new ArgumentNullException(nameof(IEasyCachingProvider));
     this.Options = options ?? throw new ArgumentNullException(nameof(OSSOptions));
 }
Beispiel #37
0
        public AliOSS()
        {
            AliyunConfigurationSection config = ConfigurationService.Instance.AliyunConfiguration;

            _endpoint   = config.OSS.EndPoint;
            _bucketName = config.OSS.BucketName;
            _client     = new OssClient(_endpoint, config.RTM.AccessKeyId, config.RTM.AccessKeySecret);
        }
 /// <summary>
 /// OSSClient构造函数, 初始化参数用
 /// </summary>
 public OSSClientManager()
 {
     this.AccessKeyId     = AppSettings["OSSAccessKeyID"];
     this.AccessKeySecret = AppSettings["OSSAccessKeySecret"];
     this.Endpoint        = AppSettings["OSSEndpoint"];
     this.OSSAddress      = AppSettings["OSSAddress"];
     this.Client          = new OssClient(this.Endpoint, this.AccessKeyId, this.AccessKeySecret);
 }
Beispiel #39
0
 static OSSHelper()
 {
     if (ossClient == null)
     {
         string accessKeyId = "ASIceatqLayAkgJp";
         string accessKeySecret = "E9wjh0SSLyG14oYBvo1LJT7f8kO5nl";
         ossClient = new OssClient(accessKeyId, accessKeySecret);
     }
 }
		private void button2_Click(object sender, EventArgs e)
		{
			var oss = new OssClient(EndPoint, AccessKeyId, AccessKeySecret);

			var images = oss.ListObjects(BucketName, "avatar");

			foreach (var image in images.ObjectSummaries)
			{
				if (image.Size > 0)
					textBox1.AppendText(string.Format("{0}, Size = {1} kb\n", image.Key, image.Size / 1000));
			}
		}
        public static void CreateEmptyFolder()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid endpoint>";

            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            const string bucketName = "<your bucket>";
            // Note: key treats as a folder and must end with slash.
            const string key = "yourfolder/";
            var created = false;
            var uploaded = false;
            try
            {
                // create bucket
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);

                // put object with zero bytes stream.
                using (MemoryStream memStream = new MemoryStream())
                {
                    PutObjectResult ret = client.PutObject(bucketName, key, memStream);
                    uploaded = true;
                    Console.WriteLine("Uploaded empty object's ETag: " + ret.ETag);
                }
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("CreateBucket Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (uploaded)
                {
                    client.DeleteObject(bucketName, key);
                }
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
        public static void SetBucketCors()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<bucket name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var req = new SetBucketCorsRequest(bucketName);
                var r1 = new CORSRule();
                // Note: AllowedOrigin & AllowdMethod must not be empty.
                r1.AddAllowedOrigin("http://www.a.com");
                r1.AddAllowedMethod("POST");
                r1.AddAllowedHeader("*");
                r1.AddExposeHeader("x-oss-test");
                req.AddCORSRule(r1);

                var r2 = new CORSRule();
                r2.AddAllowedOrigin("http://www.b.com");
                r2.AddAllowedMethod("GET");
                r2.AddExposeHeader("x-oss-test2");
                r2.MaxAgeSeconds = 1000000000;
                req.AddCORSRule(r2);

                client.SetBucketCors(req);

                var rs = client.GetBucketCors(bucketName);
                foreach (var r in rs)
                {
                    // do something with CORSRule here...
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
            finally
            {
                client.DeleteBucketCors(bucketName);
            }
        }
 public void DisabledAccessKeyTest()
 {
     try
     {
         //Key id/secret is valid but disabled
         var ossClient = new OssClient(Config.Endpoint, Config.DisabledAccessKeyId, Config.DisabledAccessKeySecret);
         ossClient.ListBuckets();
         Assert.Fail("Disabled access key should not initialize OssClient successfully");
     }
     catch(OssException e)
     {
         Assert.AreEqual(OssErrorCode.InvalidAccessKeyId, e.ErrorCode);
     }
 }
 public void InvalidAccessKeySecretTest()
 {
     try
     {
         //Key secret is invalid
         var ossClient = new OssClient(Config.Endpoint, Config.AccessKeyId, "invalidKeySecret");
         ossClient.ListBuckets();
         Assert.Fail("Invalid key secret should not initialize OssClient successfully");
     }
     catch (OssException e)
     {
         Assert.AreEqual(OssErrorCode.SignatureDoesNotMatch, e.ErrorCode);
     }
 }
        public static void SetBucketReferer()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<bucket name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var refererList = new List<string>();
                refererList.Add(" http://www.aliyun.com");
                refererList.Add(" http://www.*.com");
                refererList.Add(" http://www.?.aliyuncs.com");
                var srq = new SetBucketRefererRequest(bucketName, refererList);
                //srq.ClearRefererList();
                client.SetBucketReferer(srq);

                var rc = client.GetBucketReferer(bucketName);
                Console.WriteLine("allow?" + (rc.AllowEmptyReferer ? "yes" : "no"));
                if (rc.RefererList.Referers != null)
                {
                    for (var i = 0; i < rc.RefererList.Referers.Length; i++)
                        Console.WriteLine(rc.RefererList.Referers[i]);
                }
                else
                {
                    Console.WriteLine("Empty Referer List");
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
            finally
            {
                client.SetBucketReferer(new SetBucketRefererRequest(bucketName));
            }
        }
        private BFInfo SaveBF(BLLBFInfo bllbf, HttpPostedFileBase hf, int sysid, int bfid, int width, int height)
        {
            string filename = hf.FileName;
            string extname = System.IO.Path.GetExtension(filename).ToLower();
            string fname = System.IO.Path.GetFileNameWithoutExtension(filename);

            Stream newfile = hf.InputStream;

            BFInfo bfinfo;
            if (hf.ContentType.ToLower().Contains("image"))
            {
                Image image = System.Drawing.Image.FromStream(hf.InputStream);
                newfile = GetThumbnail(image, width, height);
            }
            newfile.Seek(0, SeekOrigin.Begin);
            OssClient oc = new OssClient(AccessKeyID, AccessKeySecret);
            string newfilename = DateTime.Now.ToString("yyMMdd") + "/" + Guid.NewGuid().ToString();
            PutObjectResult pr = oc.PutObject(BucketName, newfilename, newfile);

            if (bfid == 0)
            {
                bfinfo = new BFInfo();
                bfinfo.SysID = sysid;
                bfinfo.OrignName = fname;
                bfinfo.ExtName = extname;
                bfinfo.MineType = hf.ContentType;
                bfinfo.LastViewDateTime = bfinfo.CrtDateTime = DateTime.Now;
                bfinfo.OSSFileName = newfilename;
                bfinfo.GetCount = 0;
                bllbf.Add(bfinfo);
            }
            else
            {
                bfinfo = bllbf.Find(bfid);
                bfinfo.OrignName = fname;
                bfinfo.ExtName = extname;
                bfinfo.MineType = hf.ContentType;
                bfinfo.CrtDateTime = DateTime.Now;
                bfinfo.OSSFileName = newfilename;
                bfinfo.GetCount = 0;
                bllbf.UpDate(bfinfo);
            }
            return bfinfo;
        }
Beispiel #47
0
        protected void btnDeleteBucket_Click(object sender, EventArgs e)
        {
            OssClient ossClient = new OssClient(accessId, accessKey);
            try
            {
                ossClient.DeleteBucket(bucketName);
                Console.WriteLine("删除成功!Bucket: " + bucketName);
            }
            catch (OssException ex)
            {
                // RequestID和HostID可以在有问题时用于联系客服诊断异常。
                Console.WriteLine(string.Format("创建失败。错误代码:{0}; 错误消息:{1}。\nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode,
                    ex.Message,
                    ex.RequestId,
                    ex.HostId));

            }
        }
        public static void ListBuckets()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                // 1. Try to list all buckets.
                var buckets = client.ListBuckets();
                Console.WriteLine("List all buckets: ");
                foreach (var bucket in buckets)
                {
                    Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner);
                }

                // 2. List buckets by specified conditions, such as prefix/marker/max-keys.
                var req = new ListBucketsRequest {Prefix = "test", MaxKeys = 3, Marker = "test2"};
                var res = client.ListBuckets(req);
                buckets = res.Buckets;
                Console.WriteLine("List buckets by page: ");
                Console.WriteLine("Prefix: " + res.Prefix + ", MaxKeys: " + res.MaxKeys + ", Marker: " + res.Marker
                    + ", NextMarker: " + res.NextMaker);
                foreach (var bucket in buckets)
                {
                    Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner);
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Beispiel #49
0
        public static void PutObject()
        {
            key =DateTime.Now.ToShortDateString()+"/aaa.jpg";
            try
            {
                var credentials = GetSecurityToken();
                var ossClient = new OssClient(endpoint, credentials.AccessKeyId, credentials.AccessKeySecret, credentials.SecurityToken);

                // 1. put object to specified output stream
                using (var fs = File.Open(fileToUpload, FileMode.Open))
                {
                    var metadata = new ObjectMetadata();
                    //metadata.UserMetadata.Add("mykey1", "myval1");
                    //metadata.UserMetadata.Add("mykey2", "myval2");
                    metadata.CacheControl = "No-Cache";
                    metadata.ContentType = "image/jpeg";
                    metadata.ContentLength = fs.Length;
                    ossClient.PutObject(bucketName, key, fs);
                }

                 //2. put object to specified file
                //client.PutObject(bucketName, key, fileToUpload);

                // 3. put object from specified object with multi-level virtual directory
                //key = "folder/sub_folder/key0";
                //client.PutObject(bucketName, key, fileToUpload);

            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        public void CreateAndDeleteBucketDefaultRegionTest()
        {
            var settings = AccountSettings.Load();
            //point to default region
            var ossClient = new OssClient(settings.OssEndpoint, settings.OssAccessKeyId, settings.OssAccessKeySecret);

            //get a random bucketName
            var bucketName = OssTestUtils.GetBucketName(_className);

            //assert bucket does not exist
            Assert.IsFalse(OssTestUtils.BucketExists(ossClient, bucketName),
                string.Format("Bucket {0} should not exist before creation", bucketName));

            //create a new bucket
            ossClient.CreateBucket(bucketName);
            Assert.IsTrue(ossClient.DoesBucketExist(bucketName),
                string.Format("Bucket {0} should exist after creation", bucketName));

            //delete the bucket
            ossClient.DeleteBucket(bucketName);
            Assert.IsFalse(ossClient.DoesBucketExist(bucketName),
                string.Format("Bucket {0} should not exist after deletion", bucketName));
        }
        public static void DoesObjectExist(string bucketName, string key)
        {
            const string accessId = "<your access id>";
            const string accessKey = "<your access key>";
            const string endpoint = "<valid host name>";

            var client = new OssClient(endpoint, accessId, accessKey);

            try
            {
                var exist = client.DoesObjectExist(bucketName, key);
                Console.WriteLine("exist ? " + exist);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Beispiel #52
0
        protected void btnPutObject_Click(object sender, EventArgs e)
        {
            OssClient ossClient = new OssClient(endpoint, accessId, accessKey);
            try
            {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.ContentType = FileUpload1.PostedFile.ContentType;
                using (var fs = FileUpload1.PostedFile.InputStream)
                {
                    ossClient.PutObject(bucketName, DateTime.Now.ToString("yyyyMMddHHmmssfff"), fs, metadata);
                }
                Console.WriteLine("Bucket: " + bucketName);
            }
            catch (OssException ex)
            {
                // RequestID和HostID可以在有问题时用于联系客服诊断异常。
                Console.WriteLine(string.Format("创建失败。错误代码:{0}; 错误消息:{1}。\nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode,
                    ex.Message,
                    ex.RequestId,
                    ex.HostId));

            }
        }
        public static void CreateBucket(string bucketName)
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            var created = false;
            try
            {
                client.CreateBucket(bucketName);
                created = true;
                Console.WriteLine("Created bucket name: " + bucketName);
                client.CreateBucket(bucketName);
            }
            catch (OssException ex)
            {
                if (ex.ErrorCode == OssErrorCode.BucketAlreadyExists)
                {
                    Console.WriteLine("Bucket '{0}' already exists, please modify and recreate it.", bucketName);
                }
                else
                {
                    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
            }
            finally
            {
                if (created)
                {
                    client.DeleteBucket(bucketName);
                }
            }
        }
        public static void getObjectBySignedUrl2()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<bucket name>";
            const string key = "<object name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var metadata = client.GetObjectMetadata(bucketName, key);
                var etag = metadata.ETag;

                var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get);
                // Generates url signature for accessing specified object.
                var uri = client.GeneratePresignedUri(req);

                Console.WriteLine(uri.ToString());

                OssObject ossObject = client.GetObject(uri);
                var file = File.Open("<file to hold object content>", FileMode.OpenOrCreate);
                Stream stream = ossObject.Content;
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                file.Write(bytes, 0, bytes.Length);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Beispiel #55
0
        protected override void SaveFile()
        {
            _ossClient = new OssClient("http://oss-cn-hangzhou-internal.aliyuncs.com", AccessKeyId, AccessKeySecret);
            //阿里云上传图片

            var streamFile = new MemoryStream(File);

            var r = _ossClient.PutObject(BucketName, SavePath, streamFile);

            if (IsImage())
            {
                //图片切割处理
                new TaskFactory().StartNew(GenerateThumb);
            }
        }
Beispiel #56
0
 static OssFile()
 {
     _client = new OssClient(_endPoint, _accessId, _accessKey);
 }
        public static void putObjectBySignedUrl()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<bucket name>";
            const string key = "<object name>";

            //const string postData = "<your data to upload>";
            const string fileToUpload = "<file to upload>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                // Puts object by using URL Signature Style(two steps included).
                // Step1: Genereates url signature
                var generatePresignedUriRequest = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Put);
                var signedUrl = client.GeneratePresignedUri(generatePresignedUriRequest);

                // Step2: Prepares for stream to be uploaded and sends out this request.
                //var buffer = Encoding.UTF8.GetBytes(postData);
                //PutObjectResult result = null;
                //using (var ms = new MemoryStream(buffer))
                //{
                //    result = client.PutObject(signedUrl, ms);
                //}

                // Step2: Prepares for filepath to be uploaded and sends out this request.
                var result = client.PutObject(signedUrl, fileToUpload);

                Console.WriteLine("Uploaded File's ETag: {0}", result.ETag);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        public static void getObjectBySignedUrl()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            const string bucketName = "<bucket name>";
            const string key = "<object name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var metadata = client.GetObjectMetadata(bucketName, key);
                var etag = metadata.ETag;

                var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get);
                // Set optional properties(be blind to them usually)
                req.AddQueryParam("param1", "value1");
                req.ContentType = "text/html";
                req.ContentMd5 = etag;
                req.AddUserMetadata("mk1", "mv1");
                req.AddUserMetadata("mk2", "mv2");
                req.ResponseHeaders.CacheControl = "No-Cache";
                req.ResponseHeaders.ContentEncoding = "utf-8";
                req.ResponseHeaders.ContentType = "text/html";
                // Generates url signature for accessing specified object.
                var uri = client.GeneratePresignedUri(req);

                Console.WriteLine(uri.ToString());

                var webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.ContentType = "text/html";
                webRequest.Headers.Add(HttpRequestHeader.ContentMd5, etag);
                webRequest.Headers.Add("x-oss-meta-mk1", "mv1");
                webRequest.Headers.Add("x-oss-meta-mk2", "mv2");
                var resp = webRequest.GetResponse() as HttpWebResponse;
                var output = resp.GetResponseStream();
                var bufferSize = 2048;
                var bytes = new byte[bufferSize];
                try
                {
                    var length = 0;
                    do
                    {
                        length = output.Read(bytes, 0, bufferSize);
                        // to do something with bytes...
                    } while (length > 0);
                    output.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ex : " + ex.Message);
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
 static CNameSample()
 {
     clientConfig.IsCname = true;
     client = new OssClient(new Uri(endpoint), accessKeyId, accessKeySecret, clientConfig);
 }
        public static void GenPostPolicy()
        {
            const string endpoint = "http://oss-test.aliyun-inc.com";
            const string accessId = "0she9sx9tb809ft";
            const string accessKey = "MnBpcGpyMXF5dTc2NnU1Z2t3ZDQ=";

            var client = new OssClient(endpoint, accessId, accessKey);

            try
            {
                var expiration = DateTime.Now.AddMinutes(10);
                var policyConds = new PolicyConditions();
                policyConds.AddConditionItem("bucket", "oss-test2");
                // $ must be escaped with backslash.
                policyConds.AddConditionItem(MatchMode.Exact, PolicyConditions.CondKey, "user/eric/\\${filename}");
                policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, "user/eric");
                policyConds.AddConditionItem(MatchMode.StartWith, "x-oss-meta-tag", "dummy_etag");
                policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, 1024);

                var postPolicy = client.GeneratePostPolicy(expiration, policyConds);
                var encPolicy = Convert.ToBase64String(Encoding.UTF8.GetBytes(postPolicy));
                Console.WriteLine("Generated post policy: {0}", postPolicy);

                var requestUri = "http://oss-test2.oss-test.aliyun-inc.com";
                var boundary = "9431149156168";
                var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
                webRequest.Timeout = -1;
                webRequest.Method = "POST";
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

                var objectName = "xxx";
                var bucketName = "oss-test2";
                var signature = ComputeSignature(accessKey, encPolicy);
                Console.WriteLine(signature);
                var fileContent = "这是一行简单的测试文本";
                var requestBody = "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"key\"\r\n"
                        + "\r\n" + "user/eric/${filename}" + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"bucket\"\r\n"
                        + "\r\n" + bucketName + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"x-oss-meta-tag\"\r\n"
                        + "\r\n" + "dummy_etag_xxx" + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"OSSAccessKeyId\"\r\n"
                        + "\r\n" + accessId + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"policy\"\r\n"
                        + "\r\n" + encPolicy + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"Signature\"\r\n"
                        + "\r\n" + signature + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"file\"; filename=\"" + objectName + "\"\r\n\r\n"
                        + fileContent + "\r\n"
                        + "--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"submit\"\r\n\r\nUpload to OSS\r\n"
                        + "--" + boundary + "--\r\n";
                webRequest.ContentLength = requestBody.Length;
                using (var ms = new MemoryStream())
                {
                    var writer = new StreamWriter(ms, new UTF8Encoding());
                    try
                    {
                        writer.Write(requestBody);
                        writer.Flush();
                        ms.Seek(0, SeekOrigin.Begin);

                        webRequest.ContentLength = ms.Length;
                        using (var requestStream = webRequest.GetRequestStream())
                        {
                            ms.WriteTo(requestStream);
                        }
                    }
                    finally
                    {
                        writer.Dispose();
                    }
                }

                var response = webRequest.GetResponse() as HttpWebResponse;
                if (response.StatusCode == HttpStatusCode.NoContent)
                {
                    Console.WriteLine("Post object succeed!");
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }