public async Task UploadFileTest() { var mac = new Mac(AccessKey, SecretKey); var rand = new Random(); var key = $"UploadFileTest_{rand.Next()}.dat"; var filePath = LocalFile; var putPolicy = new PutPolicy { Scope = Bucket + ":" + key, DeleteAfterDays = 1 }; putPolicy.SetExpires(3600); var token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); var config = new Config { Zone = Zone.ZoneCnEast, UseHttps = true, UseCdnDomains = true, ChunkSize = ChunkUnit.U512K }; var target = new ResumableUploader(config); var result = await target.UploadFile(filePath, key, token, null); Console.WriteLine("chunk upload result: " + result); Assert.Equal((int)HttpCode.OK, result.Code); }
public void UploadFileTest() { Mac mac = new Mac(AccessKey, SecretKey); Random rand = new Random(); string key = string.Format("UploadFileTest_{0}.dat", rand.Next()); string filePath = LocalFile; PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Bucket + ":" + key; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Config config = new Config(); config.Zone = Zone.ZONE_CN_East; config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U512K; ResumableUploader target = new ResumableUploader(config); HttpResult result = target.UploadFile(filePath, key, token, null); Console.WriteLine("chunk upload result: " + result.ToString()); Assert.AreEqual((int)HttpCode.OK, result.Code); }
/// <summary> /// 上传文件,根据文件大小以及设置的阈值(用户初始化UploadManager时可指定该值)自动选择: /// 若文件大小超过设定阈值,使用ResumableUploader,否则使用FormUploader /// </summary> /// <param name="localFile">本地待上传的文件名</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传文件后的返回结果</returns> public HttpResult UploadFile(string localFile, string saveKey, string token) { HttpResult result = new HttpResult(); FileInfo fi = new FileInfo(localFile); if (fi.Length > PUT_THRESHOLD) { if (string.IsNullOrEmpty(recordFile)) { string recordKey = ResumeHelper.GetDefaultRecordKey(localFile, saveKey); recordFile = Path.Combine(UserEnv.GetHomeFolder(), recordKey); } if (upph == null) { upph = new UploadProgressHandler(ResumableUploader.DefaultUploadProgressHandler); } if (upctl == null) { upctl = new UploadController(ResumableUploader.DefaultUploadController); } ResumableUploader ru = new ResumableUploader(UPLOAD_FROM_CDN, CHUNK_UNIT); result = ru.UploadFile(localFile, saveKey, token, recordFile, upph, upctl); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = fu.UploadFile(localFile, saveKey, token); } return(result); }
//断点续传 public static void UploadFileResum(string key, string filePath, string uptoken, Action <string> callback) { //配置config Config config = new Config(); config.Zone = Zone.ZONE_CN_South; config.UseHttps = false; config.UseCdnDomains = false; config.ChunkSize = ChunkUnit.U512K; PutExtra put = new PutExtra(); put.ProgressHandler = (long uploadedBytes, long totalBytes) => { Debug.Log(uploadedBytes + "/" + totalBytes); }; ResumableUploader ru = new ResumableUploader(config); var result = ru.UploadFile(filePath, key, uptoken, put); if (callback != null) { callback(result.Text); } }
public string UploadImage(string filePath) { Mac mac = new Mac("TYb8ZurNoN-xrUOhnNom_q3ZdPl1OLJqUsvoP0xB", "d7ajdjoitbUiJZQY7ANw5bSf3p6K3nQA8KkGxIDq"); // 上传文件名 string key = "putty2.gif"; // 本地文件路径 //string filePath = @"E:\MY\FastDevStu\Mvc\Models\微信图片_20190508193805.gif"; // 空间名 string Bucket = "cjj81pic"; // 设置上传策略,详见:https://developer.qiniu.com/kodo/manual/1206/put-policy PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Bucket + ":" + key; putPolicy.SetExpires(3600); string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Qiniu.Storage.Config config = new Qiniu.Storage.Config(); // 设置上传区域 config.Zone = Zone.ZONE_CN_South; // 设置 http 或者 https 上传 config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U512K; ResumableUploader target = new ResumableUploader(config); PutExtra extra = new PutExtra(); //设置断点续传进度记录文件 extra.ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(filePath, key); Console.WriteLine("record file:" + extra.ResumeRecordFile); extra.ResumeRecordFile = "test.progress"; HttpResult result = target.UploadFile(filePath, key, token, extra); Console.WriteLine("resume upload: " + result.ToString()); return(result.ToString()); }
/// <summary> /// 上传大文件,支持断点续上传 /// </summary> public static void uploadBigFile() { Mac mac = new Mac(Settings.AccessKey, Settings.SecretKey); string bucket = "test"; string saveKey = "video-x1-1.mp4"; string localFile = "D:/QFL/1.mp4"; // 断点记录文件,可以不用设置,让SDK自动生成,如果出现续上传的情况,SDK会尝试从该文件载入断点记录 // SDK自动生成的文件为Path.Combine(UserEnv.GetHomeFolder(), ResumeHelper.GetDefaultRecordKey(localFile, saveKey)) // 对于不同的上传任务,请使用不同的recordFile string recordFile = "D:/QFL/resume"; PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = bucket; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; // 将PutPolicy转换为JSON字符串 string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); // 包含两个参数,并且都有默认值 // 参数1(bool): uploadFromCDN是否从CDN加速上传,默认否 // 参数2(enum): chunkUnit上传分片大小,可选值128KB,256KB,512KB,1024KB,2048KB,4096KB ResumableUploader ru = new ResumableUploader(false, ChunkUnit.U1024K); // ResumableUploader.uploadFile有多种形式,您可以根据需要来选择 // // 最简模式,使用默认recordFile和默认uploadProgressHandler // UploadFile(localFile,saveKey,token) // // 基本模式,使用默认uploadProgressHandler // UploadFile(localFile,saveKey,token,recordFile) // // 一般模式,使用自定义进度处理(监视上传进度) // UploadFile(localFile,saveKey,token,recordFile,uploadProgressHandler) // // 高级模式,包含上传控制(可控制暂停/继续 或者强制终止) // UploadFile(localFile,saveKey,token,recordFile,uploadProgressHandler,uploadController) // // 高级模式,包含上传控制(可控制暂停 / 继续 或者强制终止), 可设置最大尝试次数 // UploadFile(localFile,saveKey,token,recordFile,maxTry,uploadProgressHandler,uploadController) // 使用默认进度处理,使用自定义上传控制 UploadProgressHandler upph = new UploadProgressHandler(ResumableUploader.DefaultUploadProgressHandler); UploadController upctl = new UploadController(uploadControl); var result = ru.UploadFile(localFile, saveKey, token, recordFile, upph, upctl); Console.WriteLine(result); }
/// <summary> /// 分片上传(断点续传) /// </summary> /// <param name="key"></param> /// <param name="path"></param> /// <returns></returns> public string ChunkUpload(string key, string path) { ResumableUploader resumableUploader = new ResumableUploader(ConfigUtil); PutExtra putExtra = new PutExtra { ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(path, key) }; HttpResult httpResult = resumableUploader.UploadFile(path, key, TokenUtil, putExtra); return(httpResult.Text); }
private void Upload() { try { string key = tbUploadName.Text.Trim(); string filePath = tbFilePath.Text.Trim(); RestRequest req = new RestRequest("GetUploadToken", Method.GET); req.AddParameter("key", key); var res = AutoUpdateServiceClient.Execute(req); if (res.ErrorMessage != null) { throw new Exception(res.ErrorMessage); } string token = res.Content.Trim(new char[] { '"' }); Config config = new Config(); // 设置上传区域 config.Zone = Zone.ZONE_CN_South; // 设置 http 或者 https 上传 config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U1024K;//.U512K; ResumableUploader target = new ResumableUploader(config); PutExtra extra = new PutExtra(); extra.ProgressHandler = new UploadProgressHandler(UploadProgress); //设置断点续传进度记录文件 //extra.ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(filePath, key); extra.ResumeRecordFile = key + ".progress"; HttpResult result = target.UploadFile(filePath, AutoUpdatePath + key, token, extra); if (result.Code != (int)HttpCode.OK) { MessageBox.Show("上传失败!" + result.ToString()); } else { MessageBox.Show("上传成功!"); } } catch (Exception ex) { MessageBox.Show("出错:" + ex.Message); } finally { btnUpload.Enabled = true; } }
public void UploadFileTest() { Mac mac = new Mac(AccessKey, SecretKey); string key = FileKey2; string filePath = LocalFile2; PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = Bucket1 + ":" + key; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); ResumableUploader target = new ResumableUploader(); HttpResult result = target.UploadFile(filePath, key, token); Assert.AreEqual((int)HttpCode.OK, result.Code); }
/// <summary> /// 上传大文件,可以从上次的断点位置继续上传 /// </summary> public void UploadBigFile() { var token = QiNiuHelper.GetToken(); string saveKey = "1.mp4"; string localFile = "D:\\QFL\\1.mp4"; // 断点记录文件,可以不用设置,让SDK自动生成,如果出现续上传的情况,SDK会尝试从该文件载入断点记录 // 对于不同的上传任务,请使用不同的recordFile string recordFile = "D:\\QFL\\resume.12345"; // 包含两个参数,并且都有默认值 // 参数1(bool): uploadFromCDN是否从CDN加速上传,默认否 // 参数2(enum): chunkUnit上传分片大小,可选值128KB,256KB,512KB,1024KB,2048KB,4096KB ResumableUploader ru = new ResumableUploader(false, ChunkUnit.U1024K); // ResumableUploader.UploadFile有多种形式,您可以根据需要来选择 // // 最简模式,使用默认recordFile和默认uploadProgressHandler //UploadFile(localFile,saveKey,token) // // 基本模式,使用默认uploadProgressHandler // UploadFile(localFile,saveKey,token,recordFile) // // 一般模式,使用自定义进度处理(可以监视上传进度) // UploadFile(localFile,saveKey,token,recordFile,uploadProgressHandler) // // 高级模式,包含上传控制(可控制暂停/继续 或者强制终止) // UploadFile(localFile,saveKey,token,recordFile,uploadProgressHandler,uploadController) // // 支持自定义参数 //var extra = new System.Collections.Generic.Dictionary<string, string>(); //extra.Add("FileType", "UploadFromLocal"); //extra.Add("YourKey", "YourValue"); //uploadFile(...,extra,...) //最大尝试次数(有效值1~20),在上传过程中(如mkblk或者bput操作)如果发生错误,它将自动重试,如果没有错误则无需重试 int maxTry = 10; // 使用默认进度处理,使用自定义上传控制 UploadProgressHandler upph = new UploadProgressHandler(ResumableUploader.DefaultUploadProgressHandler); UploadController upctl = new UploadController(uploadControl); HttpResult result = ru.UploadFile(localFile, saveKey, token, recordFile, maxTry, upph, upctl); Console.WriteLine(result); }
public void uploadFile(object obj) { FileItem item = obj as FileItem; if (syncProgressPage.checkCancelSignal() && item.Length > syncSetting.ChunkUploadThreshold) { this.doneEvent.Set(); return; } string fileFullPath = item.LocalFile; if (!File.Exists(fileFullPath)) { Log.Error(string.Format("file not found error, {0}", fileFullPath)); this.doneEvent.Set(); return; } //set upload params int putThreshold = this.syncSetting.ChunkUploadThreshold; int chunkSize = this.syncSetting.DefaultChunkSize; bool uploadFromCDN = this.syncSetting.UploadFromCDN; string myDocPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string recordPath = System.IO.Path.Combine(myDocPath, "qsunsync", "resume"); if (!Directory.Exists(recordPath)) { Directory.CreateDirectory(recordPath); } Mac mac = new Mac(SystemConfig.ACCESS_KEY, SystemConfig.SECRET_KEY); //current file info FileInfo fileInfo = new FileInfo(fileFullPath); long fileLength = fileInfo.Length; string fileLastModified = fileInfo.LastWriteTimeUtc.ToFileTime().ToString(); //support resume upload string recorderKey = string.Format("{0}:{1}:{2}:{3}:{4}", this.syncSetting.LocalDirectory, this.syncSetting.TargetBucket, item.SaveKey, fileFullPath, fileLastModified); recorderKey = Hashing.CalcMD5X(recorderKey); this.syncProgressPage.updateUploadLog("准备上传文件 " + fileFullPath); PutPolicy putPolicy = new PutPolicy(); if (this.syncSetting.OverwriteDuplicate) { putPolicy.Scope = this.syncSetting.TargetBucket + ":" + item.SaveKey; } else { putPolicy.Scope = this.syncSetting.TargetBucket; } putPolicy.SetExpires(24 * 30 * 3600); string uptoken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); this.syncProgressPage.updateUploadLog("开始上传文件 " + fileFullPath); HttpResult result = null; ChunkUnit cu = (ChunkUnit)(chunkSize / (128 * 1024)); if (item.Length > putThreshold) { ResumableUploader ru = new ResumableUploader(uploadFromCDN, cu); string recordFile = System.IO.Path.Combine(recordPath, Hashing.CalcMD5X(fileFullPath)); UploadProgressHandler upph = new UploadProgressHandler(delegate(long uploaded, long total) { this.syncProgressPage.updateSingleFileProgress(taskId, fileFullPath, item.SaveKey, uploaded, fileLength); }); result = ru.UploadFile(fileFullPath, item.SaveKey, uptoken, recordFile, upph, upController); } else { FormUploader su = new FormUploader(uploadFromCDN); result = su.UploadFile(fileFullPath, item.SaveKey, uptoken); } if (result.Code == (int)HttpCode.OK) { item.Uploaded = true; this.syncProgressPage.updateUploadLog("上传成功 " + fileFullPath); this.syncProgressPage.addFileUploadSuccessLog(string.Format("{0}\t{1}\t{2}", this.syncSetting.TargetBucket, fileFullPath, item.SaveKey)); this.syncProgressPage.updateTotalUploadProgress(); } else { item.Uploaded = false; this.syncProgressPage.updateUploadLog("上传失败 " + fileFullPath + "," + result.Text); this.syncProgressPage.addFileUploadErrorLog(string.Format("{0}\t{1}\t{2}\t{3}", this.syncSetting.TargetBucket, fileFullPath, item.SaveKey, result.Text)); } this.doneEvent.Set(); }
private void UploadButton_Click(object sender, RoutedEventArgs e) { string uploadToken = this.UploadTokenTextBox.Text.Trim(); string filePath = this.UploadFileTextBox.Text.Trim(); string key = this.UploadKeyTextBox.Text; if (string.IsNullOrEmpty(uploadToken) || string.IsNullOrEmpty(filePath)) { return; } if (!this.EnableKeyCheckBox.IsChecked.Value) { key = null; } if (!File.Exists(filePath)) { return; } // 移动代码(UploadButton_Click-->CreateTokenButton_Click) @fengyh, 2016-08-17-11:29 //string mimeType = this.MimeTypeTextBox.Text.Trim(); bool checkCrc32 = false; checkCrc32 = this.CheckCrc32CheckBox.IsChecked.Value; // 移动代码(UploadButton_Click-->CreateTokenButton_Click) @fengyh, 2016-08-17-11:29 //if (mimeType.Length == 0) //{ // //mimeType = null; // mimeType = "application/octet-stream"; //} string extraParamKey1 = this.ExtraParamKeyTextBox1.Text.Trim(); string extraParamValue1 = this.ExtraParamValueTextBox1.Text.Trim(); string extraParamKey2 = this.ExtraParamKeyTextBox2.Text.Trim(); string extraParamValue2 = this.ExtraParamValueTextBox2.Text.Trim(); string extraParamKey3 = this.ExtraParamKeyTextBox3.Text.Trim(); string extraParamValue3 = this.ExtraParamValueTextBox3.Text.Trim(); string recordKey = null; //update status this.cancelUpload = false; this.UploadProgressBar.Visibility = Visibility.Visible; //start upload Task.Factory.StartNew(() => { string qetag = ETag.CalcHash(filePath); if (key == null) { recordKey = Base64.UrlSafeBase64Encode(qetag); } else { recordKey = Base64.UrlSafeBase64Encode(key + qetag); } Dictionary <string, string> extraParams = new Dictionary <string, string>(); if (!extraParams.ContainsKey(extraParamKey1)) { extraParams.Add(extraParamKey1, extraParamValue1); } if (!extraParams.ContainsKey(extraParamKey2)) { extraParams.Add(extraParamKey2, extraParamValue2); } if (!extraParams.ContainsKey(extraParamKey3)) { extraParams.Add(extraParamKey3, extraParamValue3); } System.IO.FileInfo fi = new FileInfo(filePath); Qiniu.Http.HttpResult result = new Qiniu.Http.HttpResult(); if (fi.Length > 4 * 1024 * 1024) { UploadProgressHandler upph = delegate(long u, long t) { Dispatcher.BeginInvoke((Action)(() => { this.UploadProgressBar.Value = (int)(100.0 * u / t); })); }; UploadController upc = new UploadController(UploadControl); ResumableUploader uploader = new ResumableUploader(); result = uploader.UploadFile(filePath, key, uploadToken, recordKey, 1, upph, upc, extraParams); } else { FormUploader fu = new FormUploader(); result = fu.UploadFile(filePath, key, uploadToken, extraParams); } Dispatcher.BeginInvoke((Action)(() => { this.TextBox_UploadResultText.Text = result.Text; this.TextBox_UploadResultString.Text = result.ToString(); })); }); }