コード例 #1
0
        public static void GetObjectBySignedUrlWithWebRequest(string bucketName, string key)
        {
            try
            {
                var metadata = client.GetObjectMetadata(bucketName, key);
                var etag     = metadata.ETag;

                var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get);
                req.AddQueryParam("param1", "value1");
                req.ContentType = "text/html";
                req.ContentMd5  = etag;
                req.AddUserMetadata("mk1", "mv1");
                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);

                var webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.ContentType = "text/html";
                webRequest.Headers.Add(HttpRequestHeader.ContentMd5, etag);
                webRequest.Headers.Add("x-oss-meta-mk1", "mv1");
                var resp       = webRequest.GetResponse() as HttpWebResponse;
                var output     = resp.GetResponseStream();
                var bufferSize = 2048;
                var bytes      = new byte[bufferSize];
                try
                {
                    using (StreamWriter outfile = new StreamWriter(fileToSave))
                    {
                        var length = 0;
                        do
                        {
                            length = output.Read(bytes, 0, bufferSize);
                            outfile.Write(bytes);
                        } while (length > 0);
                    }
                    output.Close();

                    Console.WriteLine("Get object by signatrue succeeded.");
                }
                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);
            }
        }
コード例 #2
0
        /// <summary>
        /// 获取鉴权后的URL,文件过期时间默认设置为100年
        /// </summary>
        /// <param name="fileName">文件名,例如:Employee/dzzBack.jpg</param>
        /// <returns></returns>
        public static string GetFileUrl(string fileName)
        {
            var key = fileName;
            var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = DateTime.Now.AddYears(100)
            };

            return(client.GeneratePresignedUri(req).ToString());
        }
コード例 #3
0
        private UploadFileOutDto UpOss(FileStream stream)
        {
            try
            {
                UploadFileOutDto dto = new UploadFileOutDto();
                if (stream == null || stream.Length <= 0)
                {
                    throw new Exception("文件不能为空!");
                }

                dto.FileName = GenerateFileName(stream.Name);

                //获取该文件的输入流
                using (var fs = stream)
                {
                    OssClient ossClient = OssManager.GetInstance(_model.AccessId, _model.AccessKey, _model.EndPoint);
                    ossClient.SetBucketAcl(_model.BucketName, CannedAccessControlList.PublicRead);
                    //将该文件流保存到OSS中
                    var ret = ossClient.PutObject(_model.BucketName, dto.FileName, fs);
                    var uri = ossClient.GeneratePresignedUri(_model.BucketName, dto.FileName);
                    dto.FilePath = $"{uri.Scheme}://{uri.Host}/{dto.FileName}";
                }

                return(dto);
            }
            catch (OssException oe)
            {
                throw new Exception($"调用OSS上传时,访问服务器端时出错。错误码Code:{oe.ErrorCode},错误信息Message:{oe.Message}");
            }
        }
コード例 #4
0
        /// <summary>
        /// 获取文件oss地址
        /// </summary>
        /// <param name="fileKey"></param>
        /// <returns></returns>
        public string GetFilePath(string fileKey)
        {
            OssClient ossClient = OssManager.GetInstance(_model.AccessId, _model.AccessKey, _model.EndPoint);
            var       uri       = ossClient.GeneratePresignedUri(_model.BucketName, fileKey);

            return($"{uri.Scheme}://{uri.Host}/{fileKey}");
        }
コード例 #5
0
        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);
            }
        }
コード例 #6
0
        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);
            }
        }
コード例 #7
0
ファイル: FileConfig.cs プロジェクト: madiantech/tkcore
        public Uri GenerateUri(OssClient client)
        {
            TkDebug.AssertArgumentNull(client, "client", this);

            return(client.GeneratePresignedUri(BucketName, ObjectName,
                                               DateTime.Now + AliyunOSSSetting.Current.UrlCacheTime));
        }
コード例 #8
0
        public static void GenerateIamgeUri(string bucketName)
        {
            try
            {
                var process = "image/resize,m_fixed,w_100,h_100";
                var req     = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
                {
                    Expiration = DateTime.Now.AddHours(1),
                    Process    = process
                };

                // 产生带有签名的URI
                var uri = client.GeneratePresignedUri(req);

                Console.WriteLine("Generate Presigned Uri:{0} with process:{1} succeeded ", uri, process);
            }
            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);
            }
        }
コード例 #9
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);
        }
コード例 #10
0
        /// <summary>
        /// 通过osskey后去ossURL
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static String GetOSSUrl(String key)
        {
            GeneratePresignedUriRequest request;

            request = new GeneratePresignedUriRequest(OssConfig.bucket, key);
            var url = client.GeneratePresignedUri(request);

            return(url.ToString());
        }
コード例 #11
0
        /// <summary>
        ///     获取图片
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="key"></param>
        public static Uri Get(string bucketName, string key)
        {
            var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = DateTime.Now.AddHours(1)
            };

            return(Client.GeneratePresignedUri(req));
        }
コード例 #12
0
ファイル: AliyunOssHelper.cs プロジェクト: shiyi2017/SYZERO
        /// <summary>
        ///   获取文件下载地址
        /// </summary>
        /// <param name="ossPath">存储到oss的文件地址,如: 20181229/20181229155625123.png</param>
        /// <param name="bucketName">系统所对应的bucketName</param>
        public static Uri GetFileUrl(string ossPath, string bucketName = "")
        {
            var req = new GeneratePresignedUriRequest(bucketName, ossPath, SignHttpMethod.Get)
            {
                Expiration = DateTime.Now.AddHours(1)
            };
            OssClient client = new OssClient(AppConfig.GetSection("AliyunOSS:Endpoint"), AppConfig.GetSection("AliyunOSS:AccessKeyId"), AppConfig.GetSection("AliyunOSS:AccessKeySecret"));

            return(client.GeneratePresignedUri(req));
        }
コード例 #13
0
        public string GeneratePresignedUrl(string bucketName, string key)
        {
            var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = DateTime.Now.AddMinutes(10)
            };
            var uri = _ossClient.GeneratePresignedUri(req);

            return(uri.ToString());
        }
コード例 #14
0
        public void AliGeneratePresignedUriTest()
        {
            string ossEndpoint        = NTKeyword.CloudFileDomain;
            string ossAccessKeyId     = "ATAI4G7BGjsCjRF2ThyDdgBo";       // 假的
            string ossAccessKeySecret = "A1VdRfHJ6k8NeklCtHjQlt7MYlRShE"; // 假的
            var    ossClient          = new OssClient(ossEndpoint, ossAccessKeyId, ossAccessKeySecret);
            var    req = new GeneratePresignedUriRequest("ntminer", "helloworld.exe", SignHttpMethod.Get)
            {
                Expiration = DateTime.Now.AddMinutes(10)
            };
            var uri = ossClient.GeneratePresignedUri(req);

            Console.WriteLine(uri.ToString());
            req = new GeneratePresignedUriRequest("ntminer", "helloworld.exe", SignHttpMethod.Get);
            uri = ossClient.GeneratePresignedUri(req);
            Console.WriteLine(uri.ToString());
            TimeSpan ts = req.Expiration - DateTime.Now;

            Console.WriteLine(ts.TotalSeconds);
            // 默认是15分钟
            Assert.IsTrue(ts.TotalSeconds > 14 * 60 && ts.TotalSeconds < 16 * 60);
        }
コード例 #15
0
ファイル: AliOssHelper.cs プロジェクト: LeviLv/Repair
        /// <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="width">设置图片的宽度</param>
        /// <param name="height">设置图片的高度</param>
        /// <returns></returns>
        public static string GetIamgeUri(string accessKeyId, string accessKeySecret, string endpoint, string bucketName, string key, float width = 100, float height = 100)
        {
            var client  = new OssClient(endpoint, accessKeyId, accessKeySecret);
            var process = $"image/resize,m_fixed,w_{width},h_{height}";
            var req     = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = DateTime.Now.AddHours(64),
                Process    = process
            };
            var uri = client.GeneratePresignedUri(req);

            return(uri.ToString());
        }
コード例 #16
0
        public string GetImageUrl(string key, ImageSize imgSize)
        {
            if (!string.IsNullOrEmpty(key) && (key.StartsWith("http:") || key.StartsWith("https:")))
            {
                return(key); // 不是存储在阿里的Oss上的图片
            }

            try
            {
                var now    = DateTime.Now;
                var expire = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0).AddYears(1);
                var bucket = GetBucketName(AttachmentType.Picture);
                switch (imgSize)
                {
                case ImageSize.Small:
                {
                    var request = new GeneratePresignedUriRequest(bucket, key);
                    request.Expiration = expire;
                    request.Process    = "image/resize,p_60";
                    return(client.GeneratePresignedUri(request)?.AbsoluteUri);
                }

                case ImageSize.Mid:
                {
                    var request = new GeneratePresignedUriRequest(bucket, key);
                    request.Expiration = expire;
                    request.Process    = "image/resize,p_50";
                    return(client.GeneratePresignedUri(request)?.AbsoluteUri);
                }

                default:
                    return(client.GeneratePresignedUri(bucket, key, expire)?.AbsoluteUri);
                }
            }
            catch
            {
                return(string.Empty);
            }
        }
コード例 #17
0
 public Uri GetGeneratePresignedUri(string fileKey, DateTime expiration)
 {
     try
     {
         var req = new GeneratePresignedUriRequest(_bucketName, fileKey, SignHttpMethod.Get)
         {
             Expiration = expiration
         };
         return(_ossClient.GeneratePresignedUri(req));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #18
0
        /// <summary>
        /// 将文件上传存储空间的方法(本SDK是用阿里云OSS作为存储空间)。
        /// 用户可以根据自身的情况重写该方法,重写时须注意该方法必须传入文件二进制流(byte[])和文件名
        /// </summary>
        /// <param name="fontfile">文件二进制流</param>
        /// <param name="objectName">文件名</param>
        /// <returns></returns>
        private string UploadOss(byte[] fontfile, string objectName)
        {
            string endpoint        = _ossConfig.Endpoint;
            string accessKeyId     = _ossConfig.AccessKeyId;
            string accessKeySecret = _ossConfig.AccessKeySecret;
            string bucketName      = _ossConfig.BucketName;

            // 创建OSSClient实例
            OssClient ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var exists = ossClient.DoesBucketExist(bucketName);
                if (exists)
                {
                    ossClient.SetBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                    ossClient.PutObject(bucketName, objectName, new MemoryStream(fontfile));
                    var expiration     = DateTime.Now.AddDays(150);
                    var fontfileUrl    = ossClient.GeneratePresignedUri(bucketName, objectName, expiration);
                    var fontfileString = fontfileUrl.ToString().Substring(0, fontfileUrl.ToString().IndexOf("?"));
                    Console.WriteLine("fontfileString: " + fontfileString);

                    return(fontfileString);
                }
                else
                {
                    throw new OssException("bucket [" + bucketName + "] is not exist!");
                }
            }
            catch (OssException oe)
            {
                Console.WriteLine("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
                Console.WriteLine("Error Message: " + oe.Message);
                Console.WriteLine("Error Code: " + oe.ErrorCode);
                Console.WriteLine("Request ID: " + oe.RequestId);
                Console.WriteLine("Host ID: " + oe.HostId);
                throw oe;
            }
            catch (ClientException ce)
            {
                Console.WriteLine("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, " +
                                  "such as not being able to access the network.");
                Console.WriteLine(ce.StackTrace);
                throw ce;
            }
        }
コード例 #19
0
        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);
            }
        }
コード例 #20
0
ファイル: TestSDK.cs プロジェクト: Jasonbourne723/HeyTom
        public static void Test()
        {
            //.aliyuncs.com

            /*client: new OSS({
             * region: 'oss-cn-shenzhen',
             * accessKeyId: 'LTAISgT8Qj4MCgAT',
             * accessKeySecret: 'smtQr62zYeRTHDCZGZ0eseA8CDdBpk',
             * // bucket: 'swyunfan'
             * bucket: 'swyunfantesting'
             * })*/

            string endpoint        = "oss-cn-shenzhen.aliyuncs.com";
            string accessKeyId     = "LTAISgT8Qj4MCgAT";
            string accessKeySecret = "smtQr62zYeRTHDCZGZ0eseA8CDdBpk";
            string bucketName;
            string objectName;
            string localFilename;

            Aliyun.OSS.Common.ClientConfiguration configuration = new Aliyun.OSS.Common.ClientConfiguration();
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret, configuration);

            var list = client.ListBuckets();

            var aa = client.GeneratePresignedUri("swyunfantesting", "test100818.jpg");

            // 上传文件。
            var result = client.PutObject("swyunfantesting", "test100818.jpg", @"G:\resource\e53c868ee9e8e7b28c424b56afe2066d.jpg");

            var obj = client.GetObject("swyunfantesting", "test100818.jpg");

            using (var requestStream = obj.Content)
            {
                byte[] buf = new byte[1024];
                var    fs  = File.Open(@"G:\resource\12313.jpg", FileMode.OpenOrCreate);
                var    len = 0;
                // 通过输入流将文件的内容读取到文件或者内存中。
                while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                {
                    fs.Write(buf, 0, len);
                }
                fs.Close();
            }
        }
コード例 #21
0
        /// <inheritdoc/>
        public async Task <string> GetBlobUrl(string containerName, string blobName, DateTime expiry,
                                              bool isDownload = false,
                                              string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            try
            {
                var httpMethod = SignHttpMethod.Get;
                return(await Task.Run(() =>
                {
                    switch (access)
                    {
                    case BlobUrlAccess.Read:
                        httpMethod = SignHttpMethod.Get;
                        break;

                    case BlobUrlAccess.All:
                    case BlobUrlAccess.Write:
                        httpMethod = SignHttpMethod.Put;
                        break;

                    case BlobUrlAccess.Delete:
                        httpMethod = SignHttpMethod.Delete;
                        break;

                    default:
                        throw new StorageException(StorageErrorCode.InvalidAccess.ToStorageError(),
                                                   new Exception("无效的访问凭据"));
                    }

                    var req = new GeneratePresignedUriRequest(containerName, blobName, httpMethod)
                    {
                        Expiration = expiry
                    };
                    var url = _ossClient.GeneratePresignedUri(req);
                    return url.AbsoluteUri;
                }));
            }
            catch (Exception ex)
            {
                throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
                                           new Exception(ex.ToString()));
            }
        }
コード例 #22
0
        /// <summary>
        /// Creates the BLOB credential.
        /// </summary>
        /// <param name="containerName">Name of the container.</param>
        /// <param name="blobIdentifier">The BLOB identifier.</param>
        /// <param name="expireOffsetInMinute">The expire offset in minute.</param>
        /// <param name="method">The method.</param>
        /// <param name="putUserMeta">The put user meta.</param>
        /// <returns></returns>
        private BinaryStorageActionCredential CreateBlobCredential(string containerName,
                                                                   string blobIdentifier, int expireOffsetInMinute, SignHttpMethod method, Action <GeneratePresignedUriRequest> putUserMeta = null)
        {
            var expiredStamp = DateTime.UtcNow.AddMinutes(expireOffsetInMinute);
            GeneratePresignedUriRequest presignRequest = new GeneratePresignedUriRequest(containerName, blobIdentifier);

            presignRequest.Expiration = expiredStamp;
            presignRequest.Method     = method;

            putUserMeta?.Invoke(presignRequest);

            return(new BinaryStorageActionCredential
            {
                Container = containerName,
                Identifier = blobIdentifier,
                CredentialExpiredStamp = expiredStamp,
                CredentialUri = client.GeneratePresignedUri(presignRequest).ToString()
            });
        }
コード例 #23
0
        //生成暂时带签名的URL
        public static void GenerateIamgeUri()
        {
            var client = new OssClient("oss-cn-shenzhen.aliyuncs.com", "LTAId7dsrQHujhU5", "O3nQOqai4yXrvGCKNbvgrKuU8f7U7p");

            try
            {
                var req = new GeneratePresignedUriRequest("igets", "igetsLogo.jpg", SignHttpMethod.Get)
                {
                    Expiration = DateTime.Now.AddSeconds(30 * 60),
                };
                // 产生带有签名的URI
                var uri = client.GeneratePresignedUri(req);
                Console.WriteLine("Uri:{0}", uri);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
コード例 #24
0
        public string GetFileUrl(string fileName, int expiredMins = 60, bool isPrivate = false)
        {
            if (isPrivate)
            {
                DateTime expired = DateTime.Now.AddHours(expiredMins * 60);

                var client   = new OssClient(_endpoint, _accessKeyId, _accessKeySecret);
                var buckName = isPrivate ? _bucketPrivate : _bucketPublic;

                //  var req = new GeneratePresignedUriRequest(buckName, fileName, SignHttpMethod.Get);
                Uri uri = client.GeneratePresignedUri(buckName, fileName);

                return(uri.ToString());
            }
            else
            {
                return("http://" + _publicHost + fileName);
            }
        }
コード例 #25
0
        /// <summary>
        /// 获取阿里OSS的链接
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public string GetFileURL(string FileName)
        {
            //生成下载URL
            var req = new GeneratePresignedUriRequest(Final.BucketName, FileName, SignHttpMethod.Get)
            {
                //设置访问链接失效时间20分钟
                Expiration = DateTime.Now.AddMinutes(20)
            };
            //创建链接
            var        uri        = Client.GeneratePresignedUri(req);
            UriBuilder uriBuilder = new UriBuilder(uri)
            {
                Scheme = "https",
                Port   = 443
            };

            //将连接转换为string
            return(uriBuilder.Uri.ToString());
        }
コード例 #26
0
        public string GetUrl(string fullPath, FileAccessMode accessMode = FileAccessMode.Open)
        {
            if (fullPath.IsNull())
            {
                return(string.Empty);
            }
            if (fullPath.StartsWith("http:", StringComparison.OrdinalIgnoreCase) || fullPath.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
            {
                return(fullPath);
            }

            //公开
            if (accessMode == FileAccessMode.Open)
            {
                return($"{_config.Domain}{HttpUtility.UrlEncode(fullPath, Encoding.UTF8)}");
            }

            //私有
            try
            {
                // 创建OSSClient实例。
                var client = new OssClient(_config.Endpoint, _config.AccessKeyId, _config.AccessKeySecret);
                // 生成签名URL
                var req = new GeneratePresignedUriRequest(_config.BucketName, fullPath, SignHttpMethod.Get)
                {
                    Expiration = DateTime.Now.AddHours(4)
                };
                var uri = client.GeneratePresignedUri(req);

                return($"{_config.Domain}{uri.PathAndQuery}");
            }
            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);
            }

            return(string.Empty);
        }
コード例 #27
0
        /// <summary>
        /// 获取图片uri
        /// </summary>
        /// <param name="keyname">上传图片的keyname</param>
        /// <param name="process">需要对图片进行的操作,可空,eg:process = "image/resize,m_fixed,w_100,h_100"</param>
        /// <returns></returns>
        public string GetImgPath(string keyname, string process = null)
        {
            try
            {
                var req = new GeneratePresignedUriRequest(bucketname, key, SignHttpMethod.Get);

                if (!string.IsNullOrWhiteSpace(process))
                {
                    req.Process    = process;
                    req.Expiration = DateTime.Now.AddSeconds(30 * 60);
                }

                // 产生带有签名的URI
                var uri = client.GeneratePresignedUri(req);
                return(uri.ToString());
            }
            catch (Exception)
            {
                throw new Exception("图片获取失败,key:" + keyname);
            }
        }
コード例 #28
0
        public ResponseRes requireResOss(string ossPath)
        {
            ResponseRes oss = new ResponseRes();

            if (string.IsNullOrEmpty(ossPath))
            {
                throw new Exception("资源请求参数错误!");
            }

            if (OssClient.DoesObjectExist(_OssConfig.bucketName, ossPath))
            {
                var req = new GeneratePresignedUriRequest(_OssConfig.bucketName, ossPath, SignHttpMethod.Get);
                var uri = _ossClient.GeneratePresignedUri(req);
                oss.downloadUrl = uri.AbsoluteUri;
            }
            else
            {
                throw new Exception("来晚了。资源失效!");
            }
            return(oss);
        }
コード例 #29
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="width">设置图片的宽度</param>
        /// <param name="height">设置图片的高度</param>
        /// <returns></returns>
        public static string GetIamgeUri(string accessKeyId, string accessKeySecret, string endpoint, string bucketName, string key, float width = 100, float height = 100)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                var process = $"image/resize,m_fixed,w_{width},h_{height}";
                var req     = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
                {
                    Expiration = DateTime.Now.AddHours(1),
                    Process    = process
                };
                var uri = client.GeneratePresignedUri(req);
                return(uri.ToString());
            }
            catch (OssException ex)
            {
                throw new Exception("阿里云请求异常", ex);
                //LogHelper.LogException<OssException>($"Msg:{ex.Message};Code:{ex.ErrorCode};RequestID:{ex.RequestId};HostID:{ex.HostId}");
            }
        }
コード例 #30
0
        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);
            }
        }
コード例 #31
0
        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);
            }
        }
コード例 #32
0
        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);
            }
        }
コード例 #33
0
        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);
            }
        }
コード例 #34
0
        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);
            }
        }
コード例 #35
0
        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);
            }
        }