Ejemplo n.º 1
0
        public void PutFileWithoutKeyTest()
        {
            IOClient target = new IOClient();
            string key = NewKey;
            PrintLn (key);
            PutExtra extra = new PutExtra (); // TODO: 初始化为适当的值
            extra.MimeType = "text/plain";
            extra.Crc32 = 123;
            extra.CheckCrc = CheckCrcType.CHECK;
            extra.Params = new System.Collections.Generic.Dictionary<string, string> ();
            PutPolicy put = new PutPolicy (Bucket);
            TmpFIle file = new TmpFIle (1024 * 10);
            target.PutFinished += new EventHandler<PutRet> ((o,e) => {
                file.Del ();
                if (e.OK) {
                    RSHelper.RSDel (Bucket, file.FileName);
                }
            });

            PutRet ret = target.PutFileWithoutKey (put.Token (),file.FileName, extra);

            //error params
            //target.PutFile("error", "error", "error", null);
            Assert.IsTrue (ret.OK, "PutFileTest Failure");
        }
Ejemplo n.º 2
0
 public KeePassQiniu.KeePassQiniuExt.UploadError UploadLocal(string name, string dbfile, out string tips) {
     Init();
     System.Net.IWebProxy webProxy = null;
     if(KeePassQiniu.KeePassQiniuConfig.Default.UseProxy) {
         webProxy = new System.Net.WebProxy(KeePassQiniu.KeePassQiniuConfig.Default.ProxyUrl, true);
     }
     // bak first
     if(KeePassQiniu.KeePassQiniuConfig.Default.AutoBackup) {
         MyRSClient moveclient = new MyRSClient();
         CallRet moveret = moveclient.Move(new EntryPathPair(KeePassQiniu.KeePassQiniuConfig.Default.QiniuBucket, name, "backup_" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + "_" + name));
         if(!moveret.OK) {
             tips = moveret.Response;
             return KeePassQiniuExt.UploadError.AUTOBAK_ERROR;
         }
     }
     // upload
     var policy = new PutPolicy(KeePassQiniu.KeePassQiniuConfig.Default.QiniuBucket);
     string upToken = policy.Token();
     PutExtra extra = new PutExtra();
     IOClient client = new IOClient();
     client.Proxy = webProxy;
     PutRet uploadret = client.PutFile(upToken, name, dbfile, extra);
     if(!uploadret.OK) {
         tips = uploadret.Response;
         return KeePassQiniuExt.UploadError.UPLOAD_ERROR;
     }
     tips = string.Empty;
     return KeePassQiniuExt.UploadError.OK;
 }
Ejemplo n.º 3
0
 /// <summary>
 /// 普通上传文件
 /// </summary>
 /// <param name="bucket"></param>
 /// <param name="key">utf-8 编码</param>
 /// <param name="fname"></param>
 public static void PutFile(string bucket, string key, string fname)
 {
     var policy = new PutPolicy(bucket, 3600);
     string upToken = policy.Token();
     PutExtra extra = new PutExtra();
     IOClient client = new IOClient();
     client.PutFile(upToken, key, fname, extra);
 }
Ejemplo n.º 4
0
 public ResponseMessage GetToken()
 {
     var policy = new PutPolicy("i4ta");
     string token = policy.Token();
     return new RFramework.Message.ResponseMessage {
         Body=new { uptoken=token}
     };
 }
Ejemplo n.º 5
0
 public static bool PutFile(string key, string fname)
 {
     var policy = new PutPolicy(bucket, 3600);
     string upToken = policy.Token();
     PutExtra extra = new PutExtra();
     IOClient client = new IOClient();
     var putFile = client.PutFile(upToken, key, fname, extra);
     return putFile.OK;
 }
Ejemplo n.º 6
0
 /// <summary>
 /// 上传文件 没有key
 /// </summary>
 /// <param name="bucket"></param>
 /// <param name="fname"></param>
 public static void PutFileWithoutKey(string bucket, string fname)
 {
     var policy = new PutPolicy(bucket, 3600);
     System.Console.WriteLine(policy);
     string upToken = policy.Token();
     IOClient target = new IOClient();
     PutExtra extra = new PutExtra();
     PutRet ret = target.PutFileWithoutKey(upToken, fname, extra);
     Console.WriteLine(ret.Response.ToString());
 }
Ejemplo n.º 7
0
        public void ResumablePutFile(string bucket, string key, System.IO.Stream stream)
        {
            Qiniu.Conf.Config.ACCESS_KEY = "_DN2l8Cb2ZjfajZWFiJ7uLsRgasrqDDlGkkq5bBS";
            Qiniu.Conf.Config.SECRET_KEY = "34Wig1rOV0wLnGGQ7E7aUDrogXdT8lDLKDsifA_l";

            PutPolicy policy = new PutPolicy(bucket,3600);
            string uptoken = policy.Token();
            Settings setting = new Settings();
            ResumablePutExtra extra = new ResumablePutExtra();
            ResumablePut client = new ResumablePut(setting, extra);
            client.PutFile(uptoken, Guid.NewGuid().ToString("N"),stream);
        }
Ejemplo n.º 8
0
		public void PutPolicyTest(){
			PutPolicy policy = new PutPolicy ("lskjd:lskd");
			policy.CallBackUrl = "callbackUrl.com";
			policy.ReturnUrl = "returnUrl.com";
			bool exp = false;
			try{
				policy.Token ();
			}catch{
				exp = true;
				Assert.IsTrue (true, "PutPolicyTest Failure1");
			}
			Assert.IsTrue (exp, "PutPolicyTest Failure2");
			exp = false;


			policy = new PutPolicy ("bucket");
			policy.CallBackUrl = "callbackUrl.com";
			try{
				policy.Token ();
			}catch{
				exp = true;
				Assert.IsTrue (true, "PutPolicyTest Failure3");
			}
			Assert.IsTrue (exp, "PutPolicyTest Failure4");
			exp = false;


			policy = new PutPolicy("bucket");
			policy.CallBackBody="uid=123";
			policy.CallBackUrl="www.qiniu.com";
			policy.DetectMime = 1;
			policy.FsizeLimit=4096;
			policy.FsizeMin=0;
			policy.InsertOnly = 1;
			policy.PersistentNotifyUrl="www.yourdomain.com/persistentNotifyUrl";
			policy.PersistentOps = "avthumb/m3u8/preset/video_16x9_440k";
			policy.CallbackHost = "180.97.211.38";
            policy.CallbackFetchKey = 0;
            policy.CallbackBodyType = "application/json";
			try {
				string result = policy.ToString();
				string expect = "{\"scope\":\"bucket\",\"callBackUrl\":\"www.qiniu.com\",\"callBackBody\":\"uid=123\",\"deadline\":0,\"insertOnly\":1,\"detectMime\":1,\"fsizeLimit\":4096,\"fsizeMin\":0,\"persistentNotifyUrl\":\"www.yourdomain.com/persistentNotifyUrl\",\"persistentOps\":\"avthumb/m3u8/preset/video_16x9_440k\",\"callbackHost\":\"180.97.211.38\",\"callbackBodyType\":\"application/json\",\"callbackFetchKey\":0}";
				//Assert.IsTrue(result==expect,"PutPolicyTest Failure5");
				Assert.AreEqual(result, expect);
			} catch (Exception ee){
				Assert.IsTrue (false, ee.Message.ToString());
			}

		}
Ejemplo n.º 9
0
 /// <summary>
 /// 上传文件测试
 /// </summary>
 /// <param name="bucket"></param>
 /// <param name="key"></param>
 /// <param name="fname"></param>
 public static string PutFile(int act)
 {
     try
     {
         Qiniu.Conf.Config.ACCESS_KEY = "ir5ydfs0HNQTSTwcvrBy82CPYPy5vxM9Lx4DfC5y";
         Qiniu.Conf.Config.SECRET_KEY = "dTh69AxJ8BQq8AJHCEPzJizRm4HDi14bomyoZpTj";
         PutPolicy policy = new PutPolicy(StringHelper.BuketName[act]);
         string iconName = initIconName(act);
         string upToken = policy.Token();
         return ReturnJson.toJson("100", "成功", new { name = iconName, token = upToken });
     }
     catch (Exception)
     {
         return ReturnJson.toJson("101", "失败",-1);
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 ///     普通上传
 /// </summary>
 /// <param name="fname">文件本地路径</param>
 /// <param name="bucket">空间名称</param>
 /// <param name="key">文件key</param>
 /// <returns>key</returns>
 public string PutFile(string fname, string bucket = "", string key = "")
 {
     if (bucket == "")
     {
         bucket = BUCKET;
     }
     var policy = new PutPolicy(bucket, 3600);
     var upToken = policy.Token();
     var extra = new PutExtra();
     var client = new IOClient();
     var ret = client.PutFile(upToken, key, fname, extra);
     if (ret != null)
     {
         return ret.key;
     }
     return "";
 }
Ejemplo n.º 11
0
        public static void PutTest()
        {
            IOClient target = new IOClient();
            string upToken = string.Empty;
            string key = LocalKey;
            //PrintLn(key);
            PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值
            extra.MimeType = "text/plain";
            extra.Crc32 = 123;
            extra.CheckCrc = CheckCrcType.CHECK;
            extra.Params = new System.Collections.Generic.Dictionary<string, string>();
            extra.Scope = Bucket+":"+key;
            PutPolicy put = new PutPolicy(extra.Scope);

            PutRet ret = target.Put(put.Token(), key, "hello Qiniu Cloud!".ToStream(), extra);

            //Assert.IsTrue(ret.OK, "PutFileTest Failure");
        }
Ejemplo n.º 12
0
        public static void Backup()
        {
            var policy = new PutPolicy(Bucket, 3600);
             string upToken = policy.Token();
             PutExtra extra = new PutExtra();
             IOClient client = new IOClient();

             string name = "db_" + System.Environment.MachineName + "_" +
                 Roo.Utils.StringBuilderHelper.GenerateStringID() + ".dbb";

             PutRet ret = client.PutFile(upToken, name, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/CleanerData/db.db", extra);

             //WebRequest request = WebRequest.Create(Server + "/DataBackup/Backup?store=" + System.Environment.MachineName + "&name=" + name);
             //WebResponse response = request.GetResponse();
             //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
             //string json = reader.ReadToEnd();
             //BackUpInfo info = Roo.Data.DataConverter.JsonToObject<BackUpInfo>(json);
             //response.Close();
        }
Ejemplo n.º 13
0
        public JsonResult GetToken()
        {
            Config.Init();
            //设置上传的空间
            String bucket = System.Configuration.ConfigurationManager.AppSettings["QN-Bucket"] ?? "zngc-intfactory"; 
            
            //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间
            PutPolicy put = new PutPolicy(bucket, 3600);

            //调用Token()方法生成上传的Token
            string upToken = put.Token();
            JsonDictionary.Add("uptoken", upToken);

            return new JsonResult()
            {
                Data = JsonDictionary,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
Ejemplo n.º 14
0
		public static List<string> RSPut(string bucket,int num)
		{
			IOClient target = new IOClient(); 
			string key = "csharp" + Guid.NewGuid().ToString();
			//PrintLn(key);
			PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值
			extra.MimeType = "text/plain";
			PutPolicy put = new PutPolicy(bucket);
			List<string> newKeys=new List<string>();
			for (int i=0; i<num; i++) {
				key = "csharp" + Guid.NewGuid ().ToString ();
				PutRet ret = target.Put (put.Token (), key,StreamEx.ToStream("Hello, Qiniu Cloud!"), extra);
				if (ret.OK) {
					newKeys.Add (key);
				}
			
			}
			return newKeys;
		}
Ejemplo n.º 15
0
 /// <summary>
 /// </summary>
 /// <param name="fname"></param>
 /// <param name="bucket"></param>
 public string ResumablePutFile(string fname, string bucket = "")
 {
     if (bucket == "")
     {
         bucket = BUCKET;
     }
     //Console.WriteLine("\n===> ResumablePutFile {0}:{1} fname:{2}", bucket, key, fname);
     var policy = new PutPolicy(bucket, 3600);
     var upToken = policy.Token();
     var setting = new Settings();
     var extra = new ResumablePutExtra();
     var client = new ResumablePut(setting, extra);
     var ret = client.PutFile(upToken, fname, Guid.NewGuid().ToString());
     if (ret != null)
     {
         return ret.Response;
     }
     return "";
 }
Ejemplo n.º 16
0
        public void PutPolicyTest()
        {
            PutPolicy policy = new PutPolicy ("lskjd:lskd");
            policy.CallBackUrl = "callbackUrl.com";
            policy.ReturnUrl = "returnUrl.com";
            bool exp = false;
            try{
                policy.Token ();
            }catch{
                exp = true;
                Assert.IsTrue (true, "PutPolicyTest Failure");
            }
            Assert.IsTrue (exp, "PutPolicyTest Failure");
            exp = false;

            policy = new PutPolicy ("bucket");
            policy.CallBackUrl = "callbackUrl.com";
            try{
                policy.Token ();
            }catch{
                exp = true;
                Assert.IsTrue (true, "PutPolicyTest Failure");
            }
            Assert.IsTrue (exp, "PutPolicyTest Failure");
            exp = false;

            policy = new PutPolicy("bucket");
            policy.AsyncOps="";
            policy.CallBackBody="uid=123";
            policy.CallBackUrl="www.qiniu.com";
            policy.DetectMime = 1;
            policy.FsizeLimit=4096;
            policy.InsertOnly = 1;
            policy.PersistentNotifyUrl="www.yourdomain.com/persistentNotifyUrl";
            policy.PersistentOps = "avthumb/m3u8/preset/video_16x9_440k";
            try {
                string result = policy.ToString();
                string expect = "{\"scope\":\"bucket\",\"callBackUrl\":\"www.qiniu.com\",\"callBackBody\":\"uid=123\",\"asyncOps\":\"\",\"deadline\":0,\"insertOnly\":1,\"detectMime\":1,\"fsizeLimit\":4096,\"persistentNotifyUrl\":\"www.yourdomain.com/persistentNotifyUrl\",\"persistentOps\":\"avthumb/m3u8/preset/video_16x9_440k\"}";
                Assert.IsTrue(result==expect,"PutPolicyTest Failure");
            } catch (Exception ee){
                Assert.IsTrue (false, "PutPolicyTest Failure");
            }
        }
Ejemplo n.º 17
0
        public QiniuToken UploadToken()
        {
            Config.ACCESS_KEY = "";
            Config.SECRET_KEY = "";
            string bucket = "ylhyh";
            PutPolicy put = new PutPolicy(bucket);
            put.CallBackUrl = "http://ylhyh.onmypc.net:90/QiniuDemo/api/QiniuCallback/Upload";

            //refer to http://developer.qiniu.com/docs/v6/api/overview/up/response/vars.html for availables
            //put.CallBackBody = "name=$(fname)&hash=$(etag)&filesize=$(fsize)&processId=$(persistentId)";
            put.CallBackBody = "name=$(fname)&key=$(key)&hash=$(etag)&filesize=$(fsize)&avinfo=$(avinfo)";

            //refer to http://api.qiniu.com/status/get/prefop?id=<persistentId> for status inquery
            put.PersistentNotifyUrl = "http://ylhyh.onmypc.net:90/QiniuDemo/api/QiniuCallback/Fop";

            // refer to http://developer.qiniu.com/docs/v6/api/reference/fop/av/segtime.html
            // refer to http://developer.qiniu.com/docs/v6/api/reference/fop/av/vframe.html
            // refer to http://developer.qiniu.com/docs/v6/api/reference/fop/saveas.html
            //String encodedEntryURI = Qiniu.Util.Base64URLSafe.Encode("ylhyh:asdfasfdasdfasdfasdf_hd.m3u8");
            //string URL = "|saveas/" + encodedEntryURI;

            string thumbnail = "vframe/jpg/offset/7";

            string thumbKey = "wobo_" + Guid.NewGuid().ToString("N") + ".jpg";
            string thumbencodedEntryURI = Qiniu.Util.Base64URLSafe.Encode(bucket + ":" + thumbKey);

            string sign = "";

            string thumbsaveas = "|saveas/" + thumbencodedEntryURI;

            //put.PersistentOps = "avthumb/m3u8/segtime/15/video_240k|vframe/jpg/offset/1";// + URL;
            put.PersistentOps = thumbnail + thumbsaveas;
            put.PersistentPipeline = "pipeline1";

            return new QiniuToken() { UpToken = put.Token() };
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 上传文件,普通上传(PutFile)
        /// </summary>
        /// <param name="bucket_name">设置上传的空间</param>
        /// <param name="local_file_path">上传文件的路径</param>
        /// <param name="ext"></param>
        public static string Upload(string bucket_name, string local_file_path, string ext)
        {
            IOClient iOClient = new IOClient();
            PutExtra extra = new PutExtra();

            //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间
            PutPolicy putPolicy = new PutPolicy(bucket_name, 3600);

            //设置上传的文件的key值
            string key = Guid.NewGuid().ToString("N") + "." + ext;

            //调用Token()方法生成上传的Token
            string upToken = putPolicy.Token();

            //调用PutFile()方法上传
            PutRet putRet = iOClient.PutFile(upToken, key, local_file_path, extra);

            //打印出相应的信息
            string result;
            if (putRet == null)
            {
                result = null;
            }
            else
            {
                if (putRet.OK)
                {
                    result = key;
                }
                else
                {
                    result = null;
                }
            }
            return result;
        }
Ejemplo n.º 19
0
        public void Write(System.IO.Stream stream)
        {
            var length = stream.Length;

            var client = new Qiniu.IO.IOClient();
            var putPolicy = new PutPolicy(FileSystem.Settings.Bucket);
            var token = putPolicy.Token(new Qiniu.Auth.digest.Mac(FileSystem.Settings.AccessKey, Encoding.UTF8.GetBytes(FileSystem.Settings.SecurityKey)));
            var result = client.Put(token, VirtualPath.TrimStart('/'), stream, null);

            if (!result.OK)
                throw new QiniuException(result.StatusCode + ", " + result.Response, result.Exception);

            _indexEntry.Length = length;
            _indexEntry.LastWriteTimeUtc = DateTime.UtcNow;

            Index.UpdateFile(UrlUtil.GetParentPath(VirtualPath), _indexEntry);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 上传文件,普通上传(Put)
        /// </summary>
        /// <param name="bucket_name">设置上传的空间</param>
        /// <param name="data">上传文件字节数据</param>
        /// <param name="ext"></param>
        /// <returns></returns>
        public static string Upload(string bucket_name, byte[] data, string ext)
        {
            IOClient iOClient = new IOClient();
            PutExtra extra = new PutExtra();

            //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间
            PutPolicy putPolicy = new PutPolicy(bucket_name, 3600u);

            //设置上传的文件的key值
            string key = Guid.NewGuid().ToString("N") + "." + ext;

            //调用Token()方法生成上传的Token
            string upToken = putPolicy.Token(null);

            PutRet putRet = null;
            using (Stream stream = new MemoryStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Position = 0L;
                putRet = iOClient.Put(upToken, key, stream, extra);
            }

            string result;
            if (putRet == null)
            {
                result = null;
            }
            else
            {
                if (putRet.OK)
                {
                    result = key;
                }
                else
                {
                    result = null;
                }
            }
            return result;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 上传文件,普通上传(Put)
        /// </summary>
        /// <param name="bucket_name">设置上传的空间</param>
        /// <param name="stream">上传文件流数据</param>
        /// <param name="ext"></param>
        /// <returns></returns>
        public static string Upload(string bucket_name, Stream stream, string ext)
        {
            IOClient iOClient = new IOClient();
            PutExtra extra = new PutExtra();

            PutPolicy putPolicy = new PutPolicy(bucket_name, 3600u);

            //设置上传的文件的key值
            string key = Guid.NewGuid().ToString("N") + "." + ext;

            string upToken = putPolicy.Token(null);

            PutRet putRet = iOClient.Put(upToken, key, stream, extra);

            string result;
            if (putRet == null)
            {
                result = null;
            }
            else
            {
                if (putRet.OK)
                {
                    result = key;
                }
                else
                {
                    result = null;
                }
            }
            return result;
        }
Ejemplo n.º 22
0
 /// <summary>
 /// 断点续上传本地文件
 /// </summary>
 /// <param name="bucket"></param>
 /// <param name="key"></param>
 /// <param name="fname"></param>
 public static void ResumablePutFile(string bucket, string key, string fname)
 {
     Console.WriteLine("\n===> ResumablePutFile {0}:{1} fname:{2}", bucket, key, fname);
     PutPolicy policy = new PutPolicy(bucket, 3600);
     string upToken = policy.Token();
     Settings setting = new Settings();
     ResumablePutExtra extra = new ResumablePutExtra();
     ResumablePut client = new ResumablePut(setting, extra);
     client.PutFile(upToken, fname, Guid.NewGuid().ToString());
 }
Ejemplo n.º 23
0
        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.FileName = "";
                open.ShowDialog();
                if (string.IsNullOrEmpty(open.FileName) || !File.Exists(open.FileName))
                    return;
                var policy = new PutPolicy(Runtime.Bucket, 3600);
                string upToken = policy.Token();
                PutExtra extra = new PutExtra();
                IOClient client = new IOClient();

                string name = "db_" + System.Environment.MachineName + "_" +
                    Roo.Utils.StringBuilderHelper.GenerateStringID() + ".dbb";

                PutRet ret = client.PutFile(upToken, name, open.FileName, extra);
            }
            catch(Exception ex)
            {
                MessageBox.Show("操作失败!" + ex.Message + ex.StackTrace);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 上传文件,普通上传(Put)
        /// </summary>
        /// <param name="bucket_name">设置上传的空间</param>
        /// <param name="key"></param>
        /// <param name="data">上传文件字节数据</param>
        /// <returns></returns>
        public static bool Upload(string bucket_name, string key, byte[] data)
        {
            IOClient iOClient = new IOClient();
            PutExtra extra = new PutExtra();

            //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间
            PutPolicy putPolicy = new PutPolicy(bucket_name, 3600u);

            //调用Token()方法生成上传的Token
            string upToken = putPolicy.Token(null);

            PutRet putRet = null;
            using (Stream stream = new MemoryStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Position = 0L;
                putRet = iOClient.Put(upToken, key, stream, extra);
            }

            return putRet != null && putRet.OK;
        }
Ejemplo n.º 25
0
        public void PutTest()
        {
            IOClient target = new IOClient();
            string key = NewKey;
            PrintLn(key);
            PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值
            extra.MimeType = "text/plain";
            extra.Crc32 = 123;
            extra.CheckCrc = CheckCrcType.CHECK;
            extra.Params = new System.Collections.Generic.Dictionary<string, string>();
            PutPolicy put = new PutPolicy(Bucket);
            target.PutFinished += new EventHandler<PutRet>((o, e) =>
            {
                if (e.OK)
                {
                    RSHelper.RSDel(Bucket, key);
                }
            });
            string token = put.Token();
            PutRet ret = target.Put(put.Token(), key, StreamEx.ToStream("Hello, Qiniu Cloud!"), extra);

            Assert.IsTrue(ret.OK, "PutFileTest Failure");
        }
Ejemplo n.º 26
0
        public bool UploadAttachment(string key)
        {
            Config.Init();
            IOClient target = new IOClient();
            PutExtra extra = new PutExtra();
            //设置上传的空间
            String bucket = System.Configuration.ConfigurationManager.AppSettings["QN-Bucket"] ?? "zngc-intfactory";

            //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间
            PutPolicy put = new PutPolicy(bucket, 3600);

            //调用Token()方法生成上传的Token
            string upToken = put.Token();
            //上传文件的路径
            String filePath = "";

            //调用PutFile()方法上传
            PutRet ret = target.PutFile(upToken, key, filePath, extra);


            return ret.OK;
        }
Ejemplo n.º 27
0
        public HttpResponseMessage UpToken()
        {
            Debug.WriteLine("UpToken");

            PutPolicy put = new PutPolicy(bucket);
            put.CallBackUrl = "http://wobo.ylhyh.onmypc.net:810/QiniuSample/api/Video/Callback";

            //refer to http://developer.qiniu.com/docs/v6/api/overview/up/response/vars.html for available variables
            //refer to http://developer.qiniu.com/docs/v6/api/reference/fop/av/avinfo.html
            //put.CallBackBody = "name=$(fname)&UploadType=$(x:UploadType)&key=$(key)&hash=$(etag)&filesize=$(fsize)&avinfo=$(avinfo)";
            put.CallBackBody = "name=$(fname)&UploadType=avatar&key=$(key)&hash=$(etag)&filesize=$(fsize)&avinfo=$(avinfo)";

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("{\"uptoken\":\"" + put.Token() + "\"}", Encoding.UTF8, "application/json");

            return response;
        }
Ejemplo n.º 28
0
 /// <summary>
 /// 上传本地文件
 /// </summary>
 /// <param name="bucket"></param>
 /// <param name="key"></param>
 /// <param name="fname"></param>
 /// <param name="putFinished">上传完成事件</param>
 public static void PutFile(string bucket, string key, string fname, EventHandler<PutRet> putFinished = null)
 {
     var policy = new PutPolicy(bucket, 3600);
     string upToken = policy.Token();
     PutExtra extra = new PutExtra();
     IOClient client = new IOClient();
     if (putFinished != null)
         client.PutFinished += putFinished;
     client.PutFile(upToken, key, fname, extra);
 }
Ejemplo n.º 29
0
        private void btnCreateFetchFile_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(txtSourceAK.Text) ||
                String.IsNullOrWhiteSpace(txtSourceSK.Text) ||
                String.IsNullOrWhiteSpace(txtSourceBucket.Text) ||
                String.IsNullOrWhiteSpace(txtSourceDomain.Text))
            {
                MessageBox.Show("Please fill-in source AK, SK, Bucket and Domain!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string sourceFileName = txtSourceBucket.Text.Trim() + "_files.txt";
            string logFileName = txtSourceBucket.Text.Trim() + ".log";

            try
            {
                this.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                SetQiniuSourceKeies();
                RSFClient rsfClient = new RSFClient(txtSourceBucket.Text.Trim());

                using (FileStream file = File.Create(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, sourceFileName)))
                {
                    StreamWriter logFileStream = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFileName));
                    List<DumpItem> items;

                    while ((items = rsfClient.Next()) != null)
                    {
                        items.ForEach((DumpItem item) =>
                        {
                            string fileUrl = GetPolicy.MakeBaseUrl(txtSourceDomain.Text.Trim(), item.Key);
                            string downloadUrl = chkPrivateBucket.Checked
                                ? GetPolicy.MakeRequest(fileUrl, 12 * 60 * 60)
                                : fileUrl;

                            if (item.Key.StartsWith("m3u8_") || item.Key.EndsWith(".m3u"))
                            {
                                /*
                                 * Special process for m3u8 files.
                                 * Replace domain.
                                 */
                                int m3uTryCount = 5;

                                while (m3uTryCount > 0)
                                {
                                    try
                                    {
                                        m3uTryCount--;
                                        var request = HttpWebRequest.Create(downloadUrl) as HttpWebRequest;
                                        request.Method = "GET";

                                        var response = request.GetResponse() as HttpWebResponse;
                                        string responseContent;

                                        using (Stream responseStream = response.GetResponseStream())
                                        {
                                            var streamReader = new StreamReader(responseStream);
                                            responseContent = streamReader.ReadToEnd();
                                            responseStream.Close();
                                            responseContent =
                                                responseContent.Replace("http://" + txtSourceDomain.Text.Trim(),
                                                    string.Empty);
                                        }

                                        MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent));
                                        SetQiniuDestKeies(); // Change Thread's Qiniu keies to Destination.

                                        var putPolicy = new PutPolicy(txtDestBacket.Text.Trim(), 12 * 60 * 60);
                                        string token = putPolicy.Token();
                                        var extra = new PutExtra();
                                        var ioClient = new IOClient();
                                        var putRet = ioClient.Put(token, item.Key, memoryStream, extra);
                                        memoryStream.Close();
                                        memoryStream.Dispose();

                                        if (putRet.StatusCode != HttpStatusCode.OK)
                                        {
                                            if (m3uTryCount > 0)
                                            {
                                                logFileStream.WriteLine(String.Format("Try process m3u8: {0}[{1}]", item.Key, m3uTryCount));
                                            }
                                            else
                                            {
                                                logFileStream.WriteLine("File upload failed:" + item.Key);
                                            }
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }

                                SetQiniuSourceKeies(); // Change back Thread's Qiniu keys to Source.
                            }
                            else
                            {

                                byte[] fileKey =
                                    Encoding.UTF8.GetBytes(downloadUrl + "\t" + item.Key + Environment.NewLine);
                                file.Write(fileKey, 0, fileKey.Length);
                            }
                        });
                    }

                    logFileStream.Flush();
                    logFileStream.Close();
                    logFileStream.Dispose();

                    file.Flush();
                    file.Close();
                    file.Dispose();
                }
            }
            finally
            {
                MessageBox.Show(
                    "Source file [" + sourceFileName + "] created." +
                        Environment.NewLine + "\t1. Please look into the log file[" + logFileName + "] to check if all of the M3U8 files have been uploaded to destination bucket!" +
                        Environment.NewLine + "\t2. Please fill-in destination information and then to generate batch file!",
                    "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Enabled = true;
                this.ResetCursor();
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 上传文件,普通上传(Put)
        /// </summary>
        /// <param name="bucket_name">设置上传的空间</param>
        /// <param name="key"></param>
        /// <param name="stream">上传文件流数据</param>
        /// <returns></returns>
        public static bool Upload(string bucket_name, string key, Stream stream)
        {
            IOClient iOClient = new IOClient();
            PutExtra extra = new PutExtra();

            PutPolicy putPolicy = new PutPolicy(bucket_name, 3600u);

            string upToken = putPolicy.Token(null);

            stream.Position = 0L;
            PutRet putRet = iOClient.Put(upToken, key, stream, extra);

            return putRet != null && putRet.OK;
        }