public static void MyUpload(string path) { Debug.Log(path); if (string.IsNullOrEmpty(path)) { return; } PutPolicy policy = new PutPolicy(qiniuBucket, 3600); string upToken = policy.Token(); string key = SystemInfo.deviceUniqueIdentifier + "_" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + Path.GetFileName(path); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut client = new ResumablePut(setting, extra); CallRet callRet = client.PutFile(upToken, path, key); ReturnBody returnBody = JsonConvert.DeserializeObject <ReturnBody>(callRet.Response); qiniufileName = returnBody.key; Debug.Log(qiniufileName); Debug.Log(callRet.Response); Debug.Log(callRet.Exception); Debug.Log(callRet.StatusCode); }
public void ResumablePutFileTest() { Settings putSetting = new Settings(); // TODO: 初始化为适当的值 string key = NewKey; ResumablePutExtra extra = new ResumablePutExtra(); extra.Notify += new EventHandler <PutNotifyEvent>(extra_Notify); extra.NotifyErr += new EventHandler <PutNotifyErrorEvent>(extra_NotifyErr); extra.Bucket = Bucket; ResumablePut target = new ResumablePut(putSetting, extra); // TODO: 初始化为适当的值 Console.WriteLine("extra.Bucket:" + extra.Bucket); string upToken = new PutPolicy(extra.Bucket).Token(new Qiniu.Auth.digest.Mac()); target.Progress += new Action <float>(target_Progress); TmpFIle file = new TmpFIle(1024 * 1024 * 4); target.PutFinished += new EventHandler <CallRet> ((o, e) => { file.Del(); if (e.OK) { RSHelper.RSDel(Bucket, key); } }); target.PutFile(upToken, file.FileName, key); //Action a = new Action (() => //{ // target.PutFile (upToken, BigFile, NewKey); //}); //a.BeginInvoke (null,null); }
public void ResumablePutFileTest() { Settings putSetting = new Settings(); // TODO: 初始化为适当的值 string key = NewKey; ResumablePutExtra extra = new ResumablePutExtra(); NameValueCollection nc = new NameValueCollection(); nc.Add("x:username", "qiniu"); extra.CallbackParams = nc; extra.Notify += new EventHandler <PutNotifyEvent>(extra_Notify); extra.NotifyErr += new EventHandler <PutNotifyErrorEvent>(extra_NotifyErr); ResumablePut target = new ResumablePut(putSetting, extra); // TODO: 初始化为适当的值 Console.WriteLine("extra.Bucket:" + Bucket); string upToken = new PutPolicy(Bucket).Token(new Qiniu.Auth.digest.Mac()); TmpFIle file = new TmpFIle(1024 * 1024 * 4); target.PutFinished += new EventHandler <CallRet> ((o, e) => { file.Del(); if (e.OK) { RSHelper.RSDel(Bucket, key); } }); CallRet ret = target.PutFile(upToken, file.FileName, key); //Action a = new Action (() => //{ // target.PutFile (upToken, BigFile, NewKey); //}); //a.BeginInvoke (null,null); }
/// <summary> /// resumable uploaded /// </summary> /// <param name="upToken"></param> /// <param name="key"></param> /// <param name="fname"></param> /// <returns></returns> public static String ResumablePutFile(string upToken, string key, string fname) { Console.WriteLine("\n===> ResumablePutFile {0} fname:{1}", key, fname); Console.WriteLine(upToken); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut client = new ResumablePut(setting, extra); CallRet ret = client.PutFile(upToken, fname, Guid.NewGuid().ToString()); if (ret.OK) { Console.WriteLine("success"); string result = ret.Response; Console.WriteLine(result); JObject jo = JObject.Parse(result); string[] valuesH = jo.Properties().Select(item => item.Value.ToString()).ToArray(); string hash = valuesH[0]; return(hash); } else { Console.WriteLine("fail"); return(""); } }
/// <summary> /// 断点续传 /// </summary> /// <param name="localFile"></param> /// <returns></returns> public static async Task <string> ResumablePutFileAsync(string localFile) { PutPolicy policy = new PutPolicy(_bucket, 3600); string upToken = policy.Token(); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut client = new ResumablePut(setting, extra); CallRet callRet = await client.PutFileAsync(upToken, localFile, new FileInfo(localFile).Name); return(callRet.StatusCode == HttpStatusCode.OK ? $"{Config.API_HOST}/{((dynamic)JObject.Parse(callRet.Response)).key}" : null); }
/// <summary> /// 断点续传 /// </summary> /// <param name="name">自定义资源名称</param> /// <param name="src">路径</param> /// <returns></returns> public static bool ResumablePutFile(string name, string src) { Console.WriteLine("\n===> ResumablePutFile {0}:{1} fname:{2}", bucket, src, name); PutPolicy policy = new PutPolicy(bucket, 3600); string upToken = policy.Token(); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut client = new ResumablePut(setting, extra); var e = client.PutFile(upToken, name, Guid.NewGuid().ToString()); return(e.OK); }
/// <summary> /// 断点续传 /// </summary> /// <param name="bucket"></param> /// <param name="key"></param> /// <param name="fname"></param> public void ResumablePutFile(string bucket, string key, string fname) { Console.WriteLine("\n===> ResumablePutFile {0}:{1} fname:{2}", bucket, key, fname); PutPolicy policy = new PutPolicy(bucket); string upToken = policy.Token(); Qiniu.IO.Resumable.Settings setting = new Qiniu.IO.Resumable.Settings(); ResumablePutExtra extra = new ResumablePutExtra(); extra.Notify += new EventHandler <PutNotifyEvent>(extra_Notify); //+= PutNotifyEvent(int blkIdx, int blkSize, BlkputRet ret);//上传进度通知事件 ResumablePut client = new ResumablePut(setting, extra); client.PutFile(upToken, fname, key); }
public static void TestUpload() { string path = EditorUtility.OpenFilePanel("Select File", "", "*"); if (string.IsNullOrEmpty(path)) { return; } PutPolicy policy = new PutPolicy(qiniuBucket, 3600); string upToken = policy.Token(); string key = SystemInfo.deviceUniqueIdentifier + "_" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + Path.GetFileName(path); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut client = new ResumablePut(setting, extra); client.PutFile(upToken, path, key); }
public static void ResumablePutFile() { Console.WriteLine("\n===> ResumablePut.PutFile"); var authPolicy = new AuthPolicy(bucketName, 3600); string upToken = authPolicy.MakeAuthTokenString(); PutAuthClient client = new PutAuthClient(upToken); PutFileRet putFileRet = ResumablePut.PutFile(client, bucketName, bigkey, null, bigFile, null, "key=<key>"); PrintRet(putFileRet); if (putFileRet.OK) { Console.WriteLine("Hash: " + putFileRet.Hash); } else { Console.WriteLine("Failed to ResumablePut.PutFile"); } }
public String ResumablePutFile(string upToken, string key, string fname) { Console.WriteLine("\n===> ResumablePutFile {0} fname:{1}", key, fname); Console.WriteLine(upToken); int nameIndex = fname.LastIndexOf('\\') + 1; uploadingFName = fname.Substring(nameIndex); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); extra.Notify += this.showNotify; extra.NotifyErr += this.showNotifyErr; extra.PutSchedule += this.showSchedule; this.notifyIcon1.ShowBalloonTip(10, "注意", uploadingFName + " 正在上传", ToolTipIcon.Info); ResumablePut client = new ResumablePut(setting, extra); //ThreadPool.QueueUserWorkItem(new WaitCallback(this.changeIco), "uploading"); Thread t = new Thread(new ParameterizedThreadStart(this.changeIco)); t.Start("uploading"); CallRet ret = client.PutFile(upToken, fname, key); t.Abort(); changeIco("normal"); if (ret.OK) { Console.WriteLine("success"); string result = ret.Response; Console.WriteLine(result); JObject jo = JObject.Parse(result); string[] valuesH = jo.Properties().Select(item => item.Value.ToString()).ToArray(); string hash = valuesH[0]; return(hash); } else { Console.WriteLine("fail"); return(""); } }
public string PutFile(string key, string fname) { _putfileRet = ""; var policy = new PutPolicy(_bucket, 7200); string upToken = policy.Token(); //PutExtra extra = new PutExtra(); //IOClient client = new IOClient(); //PutRet ret = client.PutFile(upToken, key, fname, extra); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); extra.Notify += new EventHandler <PutNotifyEvent>(extra_Notify); extra.NotifyErr += new EventHandler <PutNotifyErrorEvent>(extra_NotifyErr); ResumablePut client = new ResumablePut(setting, extra); CallRet ret = client.PutFile(upToken, fname, key); if (!ret.OK) { _putfileRet = string.Format("fsizelimit={0},deadline={1},{2},{3},{4}", policy.FsizeLimit, policy.Deadline, policy.CallBackBody, policy.ReturnBody) + ret.Response + "***exception:" + ret.Exception.ToString(); } return(_putfileRet); }
static void Main(string[] args) { const string domain = "http://obftsogus.bkt.clouddn.com/"; //设置上传的空间 String bucket = "test2"; Console.WriteLine("初始化"); Config.Init(); #region Console.WriteLine("上传测试,按键继续……"); //Console.ReadLine(); IOClient target = new IOClient(); PutExtra extra = new PutExtra(); //设置上传的文件的key值 String key = string.Format("{0}.JPG", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")); //普通上传,只需要设置上传的空间名就可以了,第二个参数可以设定token过期时间 PutPolicy put = new PutPolicy(bucket, 3600); //调用Token()方法生成上传的Token string upToken = put.Token(); Console.WriteLine("upToken:" + upToken); //上传文件的路径 String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", "测试图片.JPG"); var bytes = File.ReadAllBytes(filePath); var url = string.Empty; using (var stream = new MemoryStream(bytes)) { //调用PutFile()方法上传 PutRet ret = target.PutAsync(upToken, key, stream, extra).Result; //打印出相应的信息 Console.WriteLine(ret.Response); if (ret.OK) { url = string.Concat(domain, ret.key); Console.WriteLine("上传成功"); } else { Console.WriteLine("上传失败"); } Console.WriteLine(ret.key); } //Console.ReadLine(); #endregion #region 获取文件信息 Console.WriteLine("获取基本信息测试,按键继续……"); //Console.ReadLine(); //实例化一个RSClient对象,用于操作BucketManager里面的方法 RSClient client = new RSClient(); //调用Stat方法获取文件的信息 Entry entry = client.StatAsync(new EntryPath(bucket, key)).Result; if (entry.OK) { Console.WriteLine("获取基本信息成功"); //打印文件的hash、fsize等信息 Console.WriteLine("Hash: " + entry.Hash); Console.WriteLine("Fsize: " + entry.Fsize); Console.WriteLine("PutTime: " + entry.PutTime); Console.WriteLine("MimeType: " + entry.MimeType); //Console.ReadLine(); } else { Console.WriteLine("获取基本信息失败"); } #endregion #region 载文件 Console.WriteLine("下载文件测试,按键继续……"); //Console.ReadLine(); using (var httpClient = new HttpClient()) { using (var response = httpClient.GetAsync(url)) { if (response.Result.IsSuccessStatusCode) { var s = response.Result.Content.ReadAsByteArrayAsync().Result; var downLoadPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Concat(Guid.NewGuid().ToString("N"), ".jpg")); File.WriteAllBytes(downLoadPath, s); if (File.Exists(downLoadPath)) { Console.WriteLine("下载成功,路径:" + downLoadPath); Console.WriteLine("按任意键继续……"); //Console.ReadLine(); File.Delete(downLoadPath); } else { Console.WriteLine("下载失败"); } } } } #endregion #region 除单个文件 Console.WriteLine("删除文件测试,按任意键继续……"); //Console.ReadLine(); //实例化一个RSClient对象,用于操作BucketManager里面的方法 client = new RSClient(); var ret2 = client.DeleteAsync(new EntryPath(bucket, key)).Result; if (ret2.OK) { Console.WriteLine("删除文件" + url + "成功"); } else { Console.WriteLine("删除文件失败"); } //Console.ReadLine(); #endregion #region 视频并获取首帧(上传的视频在一天后删除) Console.WriteLine("上传视频并获取首帧(上传的视频在一天后删除),按任意键继续……"); //Console.ReadLine(); put = new PutPolicy(bucket, 3600); put.DeleteAfterDays = 1; key = string.Format("视频-{0}.mov", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")); //调用Token()方法生成上传的Token upToken = put.Token(); Console.WriteLine("upToken:" + upToken); //上传文件的路径 filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", "ios视频.mov"); bytes = File.ReadAllBytes(filePath); url = string.Empty; using (var stream = new MemoryStream(bytes)) { ResumablePutExtra putExtra = new ResumablePutExtra(); putExtra.MimeType = "application/octet-stream"; putExtra.Notify += new EventHandler <PutNotifyEvent>(extra_Notify); putExtra.NotifyErr += new EventHandler <PutNotifyErrorEvent>(extra_NotifyErr); var resumablePut = new ResumablePut(new Settings(), putExtra); //todo:视频文件较大,改为断点续传 //调用PutFile()方法上传 var ret3 = resumablePut.PutFileAsync(upToken, filePath, key).Result; //打印出相应的信息 Console.WriteLine(ret3.Response); if (ret3.OK) { //url = string.Concat(domain, ret3.key); Console.WriteLine("上传成功"); } else { Console.WriteLine("上传失败"); } // Console.WriteLine(ret3.key); } //Console.ReadLine(); Console.WriteLine("触发持久化操作,获取首帧,按任意键继续……"); //Console.ReadLine(); //实例化一个entry对象 var entryPath = new EntryPath(bucket, key); //设置转码操作参数 String fops = "vframe/jpg/offset/1/w/480/h/360"; //"vframe/jpg/offset/1/w/480/h/360/rotate/90"; //"avthumb/mp4/s/640x360/vb/1.25m"; //设置转码的队列 String pipeline = "yourpipelinename"; //可以对转码后的文件进行使用saveas参数自定义命名,当然也可以不指定文件会默认命名并保存在当前空间。 String urlbase64 = Qiniu.Util.Base64URLSafe.Encode(string.Format("{0}:视频首页.jpg", domain)); String pfops = fops;// + "|saveas/" + urlbase64; //实例化一个fop对象主要进行后续转码操作 Qiniu.RS.Pfop fop = new Qiniu.RS.Pfop(); Uri uri = new Uri("http://www.baidu.com"); var s2 = fop.DoAsync(entryPath, new[] { pfops }, uri, null, 1).Result; Console.WriteLine(s2); //Console.ReadLine(); #endregion }
/// <summary> /// 上传图片 /// </summary> /// <param name="fileData">包含图片信息的对象</param> /// <param name="imgKind">照片类型</param> /// <returns></returns> public async static Task <CommonRespMsg> UploadImageAsnyc(ButterFileToUpload fileData, UploadImageKind imgKind, CancellationToken ctoken) { var kindstr = "1:1"; if (fileData.ScaleKind == ScaleKind.Scale_3x4) { kindstr = "3:4"; } else if (fileData.ScaleKind == ScaleKind.Scale_4x3) { kindstr = "4:3"; } CommonRespMsg result = new CommonRespMsg(); try { using (var client = new HttpClient()) { Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("uid", LocalSettingHelper.GetValue("uid")); dic.Add("access_token", LocalSettingHelper.GetValue("access_token")); dic.Add("appkey", UrlHelper.APP_KEY); dic.Add("img_info", "{\"scale\":\"" + kindstr + "\"}"); dic.Add("ps", fileData.PsData); dic.Add("is_private", fileData.IsPrivate ? "1" : "0"); if (fileData.ActivityID != null) { dic.Add("activity_id", fileData.ActivityID); } if (fileData.OriginalImageID != -1) { dic.Add("ding_imgid", fileData.OriginalImageID.ToString()); } var resp = await client.PostAsync(new Uri(imgKind == UploadImageKind.Photo?UrlHelper.UploadImageUrl:UrlHelper.UploadAvatarUrl), new HttpFormUrlEncodedContent(dic)); var json = JsonObject.Parse(await resp.Content.ReadAsStringAsync()); var token = JsonParser.GetStringFromJsonObj(json, "token"); var key = JsonParser.GetStringFromJsonObj(json, "key"); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut rclient = new ResumablePut(setting, extra); extra.Notify += ((sendern, en) => { }); ctoken.ThrowIfCancellationRequested(); var ioresult = await Task.Run(async() => { ctoken.ThrowIfCancellationRequested(); return(await rclient.PutFile(token, fileData.File.Path, key, ctoken)); }); if (!ioresult.OK) { throw new APIException(int.Parse(ioresult.StatusCode.ToString()), ioresult.Exception.Message); } else { return(result); } } } catch (APIException) { result.IsSuccessful = false; return(result); } catch (OperationCanceledException) { throw; } catch (Exception ee) { var task = ExceptionHelper.WriteRecord(ee, nameof(CloudServices), nameof(UploadImageAsnyc)); var resultMsg = new CommonRespMsg() { IsSuccessful = false, ErrorMsg = ee.Message }; return(resultMsg); } }