public AliyunOssPostPolicy BuildStartWithPolicy(string fileKeyStartWith, int expireSeconds = 60,
                                                        int maxSize = 8 * 1024 * 1024)
        {
            var expiration       = DateTime.Now.AddSeconds(expireSeconds);
            var policyConditions = new PolicyConditions();

            policyConditions.AddConditionItem("bucket", Options.Bucket);
            // $ must be escaped with backslash.
            policyConditions.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, fileKeyStartWith);
            policyConditions.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, maxSize); //大小限制

            var postPolicy = Client.GeneratePostPolicy(expiration, policyConditions);
            var encPolicy  = Convert.ToBase64String(Encoding.UTF8.GetBytes(postPolicy));

            var signature = ComputeSignature(Options.AccessKey, encPolicy);

            var host = (Options.CdnHost ?? Options.Host).TrimEnd('/');

            return(new AliyunOssPostPolicy
            {
                AccessId = Options.AccessId,
                Expire = expiration.GetIntDate(),
                Policy = encPolicy,
                Signature = signature,
                Host = Options.Host,
                Dir = fileKeyStartWith
            });
        }
예제 #2
0
파일: OssHelper.cs 프로젝트: yescent/emud
        public async Task <OssTokenModel> GetToken()
        {
            var targetDir = $"{ DateTime.Now:yyyyMMdd}/{Guid.NewGuid()}";

            OssClient client = new OssClient(_appConfig.Aliyun.Endpoint, _appConfig.Aliyun.AccessKeyId, _appConfig.Aliyun.AccessKeySecret);
            //密钥过期时间为10分钟
            var expiration  = DateTime.Now.AddSeconds(10);
            var policyConds = new PolicyConditions();

            policyConds.AddConditionItem("bucket", _appConfig.Aliyun.BucketName);
            policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, targetDir);
            //限制传输文件大小10M
            policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, 10240000);
            var postPolicy = client.GeneratePostPolicy(expiration, policyConds);
            var encPolicy  = Convert.ToBase64String(Encoding.UTF8.GetBytes(postPolicy));
            var signature  = ComputeSignature(_appConfig.Aliyun.AccessKeySecret, encPolicy);
            var tempRet    = new OssTokenModel
            {
                Key            = targetDir,
                Bucket         = _appConfig.Aliyun.BucketName,
                OSSAccessKeyId = _appConfig.Aliyun.AccessKeyId,
                Policy         = encPolicy,
                Signature      = signature,
                Endpoint       = $"https://{_appConfig.Aliyun.BucketName}.oss-cn-hangzhou.aliyuncs.com"
            };

            return(await Task.FromResult(tempRet));
        }
예제 #3
0
        //Object
        public string GetObjectSignedUrl(string bucketName, string key, Dictionary <string, string> queryParams, Dictionary <string, string> userMataData)
        {
            var policyConds = new PolicyConditions();
            var client      = this.Client;
            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)
            if (queryParams != null)
            {
                foreach (var item in queryParams)
                {
                    req.AddQueryParam(item.Key, item.Value);
                }
            }
            if (userMataData != null)
            {
                foreach (var item in userMataData)
                {
                    req.AddQueryParam(item.Key, item.Value);
                }
            }

            req.ContentType = "text/html";
            req.ContentMd5  = etag;
            req.ResponseHeaders.CacheControl    = "No-Cache";
            req.ResponseHeaders.ContentEncoding = "utf-8";
            req.ResponseHeaders.ContentType     = "text/html";
            var uri = client.GeneratePresignedUri(req);

            return(uri.ToString());
        }
예제 #4
0
파일: OssHelper.cs 프로젝트: Seaear/s-donet
        /// <summary>
        /// 获取oss上传签名
        /// </summary>
        public object GetUploadSignature(string bucketName, string dir, int uploadExpiration, int maxUploadSize, out string msg)
        {
            msg = string.Empty;
            try
            {
                var deadline = DateTime.Now.AddSeconds(uploadExpiration);
                PolicyConditions policyConds = new PolicyConditions();
                policyConds.AddConditionItem("bucket", bucketName);
                policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, maxUploadSize);
                var postPolicy = Clinet.GeneratePostPolicy(deadline, policyConds);
                if (string.IsNullOrWhiteSpace(postPolicy))
                {
                    throw new Exception("生成oss请求策略失败!");
                }

                var encPolicy = Convert.ToBase64String(Encoding.UTF8.GetBytes(postPolicy));
                var host      = BuildOssRequestUrl(_endpoint, bucketName);
                var signature = ComputeSignature(_accessKeySecret, encPolicy);

                return(new
                {
                    accessid = _accessKeyId,
                    policy = encPolicy,
                    signature = signature,
                    host = host,
                    dir = dir
                });
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(null);
            }
        }
예제 #5
0
        /// <summary>
        /// 获取oss凭证
        /// </summary>
        /// <returns></returns>
        public OssSignModel GetOssSign()
        {
            callbackparam.callbackUrl = callbackUrl;
            var              host        = string.Format("http://{0}.{1}", bucket, endpoint);
            OssClient        client      = new OssClient(endpoint, accessId, accessKey);
            DateTime         expiration  = DateTime.Now.AddSeconds(expireTime);
            PolicyConditions policyConds = new PolicyConditions();

            policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 0, 1050289624);
            policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);

            string postPolicy    = client.GeneratePostPolicy(expiration.AddHours(8), policyConds);
            string encodedPolicy = Convert.ToBase64String(Encoding.UTF8.GetBytes(postPolicy.ToCharArray()));
            string postSignature = HmacSHA1Signature(accessKey, encodedPolicy);

            var ossmodel = new OssSignModel();

            ossmodel.dir       = dir;
            ossmodel.host      = host;
            ossmodel.accessid  = accessId;
            ossmodel.policy    = encodedPolicy;
            ossmodel.signature = postSignature;
            ossmodel.expire    = (expiration.Ticks - BaseTime.Ticks) / 10000000 - 8 * 60 * 60;
            ossmodel.callback  = Convert.ToBase64String(Encoding.UTF8.GetBytes(JSON.Serialize(callbackparam).ToCharArray()));
            return(ossmodel);
        }
예제 #6
0
        /// <summary>
        /// Web直传签名方法
        /// </summary>
        /// <param name="dir">上传的目标文件夹</param>
        /// <param name="min">签名有效期限</param>
        /// <returns>签名信息</returns>
        public static OssSignature SignGen(string dir, int min)
        {
            var now        = DateTime.Now;
            var ex         = now.AddMinutes(min);
            var policyCods = new PolicyConditions();

            policyCods.AddConditionItem("content-length-range", 0L, 1048576000L);
            policyCods.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);
            var      postPolicy    = ossClient.GeneratePostPolicy(ex, policyCods);
            var      binaryData    = Encoding.UTF8.GetBytes(postPolicy);
            var      encodedPolicy = Convert.ToBase64String(binaryData);
            var      hmac          = new HMACSHA1(Encoding.UTF8.GetBytes(AccessKeySecret));
            var      hashBytes     = hmac.ComputeHash(Encoding.UTF8.GetBytes(encodedPolicy));
            var      signature     = Convert.ToBase64String(hashBytes);
            DateTime startTime     = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

            return(new OssSignature
            {
                AccessID = AccessKeyID,
                Policy = encodedPolicy,
                Signature = signature,
                Dir = dir,
                EndPoint = Endpoint,
                Expire = (long)(ex - startTime).TotalMilliseconds,
                OSSHost = Host,
            });
        }
예제 #7
0
        /// <summary>
        /// 获取上传参数
        /// </summary>
        /// <param name="bucket_name"></param>
        /// <param name="category"></param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        private static Resp <BucketUploadPara> GetUploadPara(string bucket_name, string category, string userId)
        {
            var osappInfo = AppReqContext.Identity;

            var domain = GetDomainByBucket(bucket_name);

            if (string.IsNullOrEmpty(domain))
            {
                return(new Resp <BucketUploadPara>().WithResp(RespTypes.NoPermission, "没有当前图片空间的上传权限"));
            }

            var patStr = new StringBuilder();

            if (AppInfoHelper.IsDev)
            {
                patStr.Append("test/");
            }

            patStr.Append(osappInfo.tenant_id).Append("/")
            .Append((int)osappInfo.app_type).Append("-").Append(userId).Append("/")
            .Append(category).Append("/")
            .Append(DateTime.Now.ToUtcMilliSeconds());

            var key = patStr.ToString();


            var expiration = DateTime.Now.AddMinutes(3);

            //var callBack = GetCallBack(key);
            var policyConds = new PolicyConditions();

            policyConds.AddConditionItem("bucket", bucket_name);
            policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, key);
            //policyConds.AddConditionItem("callback", callBack);

            var encPostPolicy = policyConds.GeneratePostPolicyJsonBase64(expiration);
            var signature     = HMACSHA.EncryptBase64(encPostPolicy, _aliConfig.AppSecret);
            var bucketConfig  = new BucketUploadPara();

            bucketConfig.paras.Add("key", key);
            bucketConfig.paras.Add("OSSAccessKeyId", _aliConfig.AppId);
            bucketConfig.paras.Add("policy", encPostPolicy);
            bucketConfig.paras.Add("signature", signature);
            //bucketConfig.paras.Add("callback", callBack);

            bucketConfig.upload_url = domain;

            return(new Resp <BucketUploadPara>(bucketConfig));
        }
예제 #8
0
        public async Task <OssPolicyResult> Policy()
        {
            OssPolicyResult result = new OssPolicyResult();
            string          dir    = AppSettings.ALiYun.DirPrefix + DateTime.Now.ToString("yyyyMMdd");
            //long expireEndTime =DateTime.Now.Millisecond + AppSettings.ALiYun.Expire * 1000;
            DateTime         expiration = DateTime.Now.AddMilliseconds(AppSettings.ALiYun.Expire * 1000);
            long             maxSize    = AppSettings.ALiYun.MaxSize * 1024 * 1024;
            OssCallbackParam callback   = new OssCallbackParam();

            callback.CallbackUrl      = AppSettings.ALiYun.Callback;
            callback.CallbackBody     = "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}";
            callback.CallbackBodyType = "application/x-www-form-urlencoded";
            string action = "http://" + AppSettings.ALiYun.BucketName + "." + AppSettings.ALiYun.EndPoint;

            try
            {
                PolicyConditions policyConds = new PolicyConditions();
                policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 0, maxSize);
                policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);
                OssClient ossClient    = new OssClient(action, AppSettings.ALiYun.AccessKeyId, AppSettings.ALiYun.AccessKeySecret);
                string    postPolicy   = ossClient.GeneratePostPolicy(expiration, policyConds);
                byte[]    binaryData   = postPolicy.GetBytes(Encoding.UTF8);
                string    policy       = Convert.ToBase64String(binaryData);
                string    signature    = ComputeSignature(AppSettings.ALiYun.AccessKeySecret, policy);
                string    callbackData = Convert.ToBase64String(callback.ToJson().ToString().GetBytes(Encoding.UTF8));
                // 返回结果
                result.AccessKeyId = AppSettings.ALiYun.AccessKeyId;
                result.Policy      = policy;
                result.Signature   = signature;
                result.Dir         = dir;
                result.Callback    = callbackData;
                result.Host        = action;
            }
            catch (Exception e)
            {
                Logger.Log(LogLevel.Error, "签名生成失败", e);
            }
            return(result);
        }
예제 #9
0
        public JObject GetSignature(string bucket, string dir)
        {
            DateTime now              = DateTime.Now;
            DateTime dateTime         = now.AddSeconds(60.0);
            var      policyConditions = new PolicyConditions();

            policyConditions.AddConditionItem("content-length-range", 0L, 1048576000L);
            policyConditions.AddConditionItem(MatchMode.StartWith, "key", dir);

            var policy  = EncodingHelper.ToBase64(Client.GeneratePostPolicy(dateTime, policyConditions));
            var value   = CryptoHelper.ComputeSHA1Signature(Access.AccessKeySecret, policy);
            var scheme  = App.Context.Request.GetScheme();
            var jObject = new JObject();

            jObject["accessid"]  = Access.AccessKeyId;
            jObject["policy"]    = policy;
            jObject["signature"] = value;
            jObject["dir"]       = dir + "_" + now.ToYMD();
            jObject["host"]      = scheme + "://" + bucket + "." + Access.Endpoint;
            jObject["expire"]    = dateTime.ToUnix();

            return(jObject);
        }
        public static void GenPostPolicy(string bucketName)
        {
            try
            {
                var expiration  = DateTime.Now.AddMinutes(10);
                var policyConds = new PolicyConditions();
                policyConds.AddConditionItem("bucket", bucketName);
                // $ 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 = endpoint + "/" + bucketName;
                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 signature  = ComputeSignature(accessKeySecret, encPolicy);

                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" + accessKeyId + "\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);
            }
        }
예제 #11
0
        /// <summary>
        /// 获取服务端直传签名(policy和callback)
        /// </summary>
        /// <param name="ossCallbackUrl">OSS往这个机器发送的url请求</param>
        /// <param name="ossCallbackHost">OSS发送这个请求时,请求头部所带的Host头</param>
        /// <param name="tips">提示信息</param>
        /// <param name="reqOssEndpoint">ossEndpoint(默认访问内网)</param>
        /// <param name="ossDir">上传目录 默认:"tools/webUpload/"</param>
        /// <param name="expireTime">过期时间(默认30秒)</param>
        /// <returns></returns>
        public Dictionary <string, string> GetSign(string ossCallbackUrl, string ossCallbackHost, out string tips, string reqOssEndpoint = "", string ossDir = "tools/webUpload/", long expireTime = 30)
        {
            if (Config == null)
            {
                throw new Exception("请先配置OssConfig");
            }
            if (string.IsNullOrEmpty(reqOssEndpoint))
            {
                reqOssEndpoint = Config.OssEndpointIn;//默认内网
            }
            string host;

            if (string.IsNullOrEmpty(Config.OssHost))
            {
                host = Config.OssProtocol + Config.OssBucketName + "." + reqOssEndpoint;
            }
            else if (Config.OssHost.Contains("http://") || Config.OssHost.Contains("https://"))
            {
                host = Config.OssHost;
            }
            else
            {
                host = Config.OssProtocol + Config.OssHost;
            }
            var client = new OssClient(reqOssEndpoint, Config.OssAccessKeyId, Config.OssAccessKeySecret);

            try
            {
                var expiration  = DateTime.Now.AddMilliseconds(expireTime * 1000);
                var policyConds = new PolicyConditions();
                policyConds.AddConditionItem(PolicyConditions.CondContentLengthRange, 0L, 1048576000L);
                policyConds.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, ossDir);
                var postPolicy     = client.GeneratePostPolicy(expiration, policyConds);
                var binaryData     = Encoding.UTF8.GetBytes(postPolicy);
                var encodedPolicy  = Convert.ToBase64String(binaryData);
                var hmac           = new HMACSHA1(Encoding.UTF8.GetBytes(Config.OssAccessKeySecret));
                var hashBytes      = hmac.ComputeHash(Encoding.UTF8.GetBytes(encodedPolicy));
                var postSignature  = Convert.ToBase64String(hashBytes);
                var ts             = expiration.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var randomFileName = "oss" + Guid.NewGuid().ToString().Replace("-", "");

                var signDic = new Dictionary <string, string>
                {
                    { "accessid", Config.OssAccessKeyId },
                    { "host", host },
                    { "policy", encodedPolicy },
                    { "signature", postSignature },
                    { "expire", Convert.ToInt64(ts.TotalSeconds).ToString() },
                    { "dir", ossDir },
                    { "filename", randomFileName }
                };
                var callback = JsonConvert.SerializeObject(new
                {
                    callbackUrl      = ossCallbackUrl,
                    callbackHost     = ossCallbackHost,
                    callbackBody     = "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}", //OSS请求时,发送给应用服务器的内容,可以包括文件的名字、大小、类型,如果是图片可以是图片的高度、宽度
                    callbackBodyType = "application/x-www-form-urlencoded"                                                                         //请求发送的Content-Type
                });
                callback = Convert.ToBase64String(Encoding.UTF8.GetBytes(callback));
                signDic.Add("callback", callback);
                tips = "获取成功";
                return(signDic);
            }
            catch (Exception ex)
            {
                tips = ex.Message;
                return(null);
            }
        }
        public static void GenPostPolicy(string bucketName)
        {
            try
            {
                var expiration = DateTime.Now.AddMinutes(10);
                var policyConds = new PolicyConditions();
                policyConds.AddConditionItem("bucket", bucketName);
                // $ 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 = endpoint + "/" + bucketName;
                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 signature = ComputeSignature(accessKeySecret, encPolicy);

                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" + accessKeyId + "\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);
            }
        }
예제 #13
0
 public void Init()
 {
     instance = new PolicyConditions();
 }
예제 #14
0
        public static void GenPostPolicy222(string bucketName)
        {
            try
            {
                var expiration  = DateTime.Now.AddMinutes(10);
                var policyConds = new PolicyConditions();
                policyConds.AddConditionItem("bucket", bucketName);
                // $ 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 = BuildRequestUri(endpoint, bucketName);
                System.Console.WriteLine("RequestUri:" + requestUri);
                var boundary   = "9431149156168";
                var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
                webRequest.Timeout     = -1;
                webRequest.Method      = "POST";
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;



                string filepath   = @"D:\xiangmu\pdf\海康威视2014年年度报告.PDF";
                var    objectName = System.IO.Path.GetFileName(filepath);

                var signature = ComputeSignature(accessKeySecret, encPolicy);


                var before = "--" + 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" + accessKeyId + "\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"
                ;              //*/

                var after = "\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;


                byte[] beforeBytes = Encoding.UTF8.GetBytes(before);



                byte[] afterBytes = Encoding.UTF8.GetBytes(after);

                long filesize = 0;
                using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    filesize = fs.Length;
                }

                webRequest.ContentLength = beforeBytes.Length + afterBytes.Length + filesize;

                using (Stream postStream = webRequest.GetRequestStream())
                {
                    postStream.ReadTimeout  = 1000 * 60;
                    postStream.WriteTimeout = 1000 * 60;

                    postStream.Write(beforeBytes, 0, beforeBytes.Length);

                    //   postStream.Write(contentBytes,0,contentBytes.Length);

                    using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                    {
                        int    bytesRead  = 0;
                        long   bytesSoFar = 0;
                        byte[] buffer     = new byte[10240];
                        while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            bytesSoFar += bytesRead;
                            postStream.Write(buffer, 0, bytesRead);
                            var UploadProgress = bytesSoFar * 1.0 / fs.Length;
                        }
                    }

                    postStream.Write(afterBytes, 0, afterBytes.Length);
                    postStream.Close();
                }


                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);
            }
        }