/// <summary> /// 上传到七牛 /// </summary> /// <param name="myStream"></param> /// <param name="filename"></param> /// <param name="servePath">上传成功的路径</param> /// <returns></returns> public static HttpResult UploadFile(Stream myStream, string filename, out string servePath) { //code为200成功 HttpResult result = new HttpResult() { Code = 1 }; servePath = ""; try { // 上传文件名 servePath = $"{Guid.NewGuid().ToString().Replace("-", "")}{filename}"; 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(); string token = GetToken(); result = target.UploadStream(myStream, servePath, token, extra); } catch (Exception ex) { LogHelper.WriteLog(ex, "QiniutokenHelper/UploadFile"); } return(result); }
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); }
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()); }
public void CreateTemplate() { DocumentsService service = new DocumentsService(applicationName); DocumentEntry entry = new DocumentEntry(); // Set the document title entry.Title.Text = spreadsheetName; entry.IsSpreadsheet = true; // Set the media source entry.MediaSource = new MediaFileSource(GetStreamWithTemplate(), applicationName, "text/csv"); // Define the resumable upload link Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri); link.Rel = ResumableUploader.CreateMediaRelation; entry.Links.Add(link); // Set the service to be used to parse the returned entry entry.Service = service; // Instantiate the ResumableUploader component. ResumableUploader uploader = new ResumableUploader(); // Start the upload process uploader.Insert(new ClientLoginAuthenticator(applicationName, ServiceNames.Documents, userName, password), entry); }
static void Main(string[] args) { DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1"); // TODO: Instantiate an Authenticator object according to your authentication // mechanism (e.g. OAuth2Authenticator). // Authenticator authenticator = ... // Instantiate a DocumentEntry object to be inserted. DocumentEntry entry = new DocumentEntry(); // Set the document title entry.Title.Text = "Legal Contract"; // Set the media source entry.MediaSource = new MediaFileSource("c:\\contract.txt", "text/plain"); // Define the resumable upload link Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri); link.Rel = ResumableUploader.CreateMediaRelation; entry.Links.Add(link); // Set the service to be used to parse the returned entry entry.Service = service; // Instantiate the ResumableUploader component. ResumableUploader uploader = new ResumableUploader(); // Set the handlers for the completion and progress events uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnDone); uploader.AsyncOperationProgress += new AsyncOperationProgressEventHandler(OnProgress); // Start the upload process uploader.InsertAsync(authenticator, entry, new object()); }
/// <summary> /// 根据文件字节数组上传 /// </summary> /// <param name="param">文件流上传配置</param> /// <param name="isResume">是否允许续传(续传采用非表单提交方式)</param> /// <returns></returns> public UploadResultDto UploadByteArray(UploadByByteArrayParam param, bool isResume = false) { var uploadPersistentOps = GetUploadPersistentOps(param.UploadPersistentOps); string token = GetUploadCredentials(QiNiuConfig, new UploadPersistentOpsParam(param.Key, uploadPersistentOps)); if (isResume) { ResumableUploader target = new ResumableUploader(Core.Tools.GetConfig(QiNiuConfig, uploadPersistentOps)); HttpResult result = target.UploadStream(param.ByteArray.ConvertToStream(), param.Key, token, GetPutExtra(uploadPersistentOps)); bool res = result.Code == (int)HttpCode.OK; return(new UploadResultDto(res, result, res ? "成功" : result.ToString())); } else { FormUploader target = new FormUploader(Core.Tools.GetConfig(QiNiuConfig, uploadPersistentOps)); HttpResult result = target.UploadData(param.ByteArray, param.Key, token, GetPutExtra(uploadPersistentOps)); bool res = result.Code == (int)HttpCode.OK; return(new UploadResultDto(res, result, res ? "成功" : result.ToString())); } }
//断点续传 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 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); }
/// <summary> /// [异步async]上传文件 /// </summary> /// <param name="localFile">本地待上传的文件名</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传文件后的返回结果</returns> public async Task <HttpResult> UploadFileAsync(StorageFile localFile, string saveKey, string token) { HttpResult result = new HttpResult(); var fi = await localFile.GetBasicPropertiesAsync(); if (fi.Size > (ulong)PUT_THRESHOLD) { if (recordFile == null) { string recordKey = ResumeHelper.GetDefaultRecordKey(localFile.Path, saveKey); recordFile = await(await UserEnv.GetHomeFolderAsync()).CreateFileAsync(recordKey, CreationCollisionOption.OpenIfExists); } 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 = await ru.UploadFileAsync(localFile, saveKey, token, recordFile, upph, upctl); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = await fu.UploadFileAsync(localFile, saveKey, token); } return(result); }
/// <summary> /// [异步async]上传文件 /// </summary> /// <param name="localFile">本地待上传的文件名</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传文件后的返回结果</returns> public async Task <HttpResult> UploadFileAsync(string localFile, string saveKey, string token) { HttpResult result = new HttpResult(); var fi = new FileInfo(localFile); if (fi.Length > PUT_THRESHOLD) { if (recordFile == null) { 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 = await ru.UploadFileAsync(localFile, saveKey, token, recordFile, upph, upctl); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = await fu.UploadFileAsync(localFile, saveKey, token); } return(result); }
public async Task UploadToYouTube(HttpPostedFile postedFile, string title) { UploadingDispatcher.SetProgress(uploadId, 2); Video video = new Video(); video.Title = title; video.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema)); video.Private = false; video.MediaSource = new MediaFileSource(postedFile.InputStream, postedFile.FileName, postedFile.ContentType); var link = new AtomLink("http://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads"); link.Rel = ResumableUploader.CreateMediaRelation; video.YouTubeEntry.Links.Add(link); var youtubeApiKey = ConfigurationManager.AppSettings["youtubeApiKey"]; var applicationName = ConfigurationManager.AppSettings["applicationName"]; var youtubeUserName = ConfigurationManager.AppSettings["youtubeUserName"]; var youtubePassword = ConfigurationManager.AppSettings["youtubePassword"]; var youtubeChunksize = int.Parse(ConfigurationManager.AppSettings["youtubeChunksize"]); var resumableUploader = new ResumableUploader(youtubeChunksize); resumableUploader.AsyncOperationCompleted += resumableUploader_AsyncOperationCompleted; resumableUploader.AsyncOperationProgress += resumableUploader_AsyncOperationProgress; var youTubeAuthenticator = new ClientLoginAuthenticator(applicationName, ServiceNames.YouTube, youtubeUserName, youtubePassword); youTubeAuthenticator.DeveloperKey = youtubeApiKey; resumableUploader.InsertAsync(youTubeAuthenticator, video.YouTubeEntry, uploadId); }
public void ResumeUploadFileTest() { Mac mac = new Mac(AccessKey, SecretKey); Random rand = new Random(); string key = string.Format("UploadFileTest_{0}.dat", rand.Next()); string filePath = LocalFile; System.IO.Stream fs = System.IO.File.OpenRead(filePath); 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.UseHttps = true; config.Zone = Zone.ZONE_CN_East; 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.UploadStream(fs, key, token, extra); Console.WriteLine("resume upload: " + result.ToString()); Assert.AreEqual((int)HttpCode.OK, result.Code); }
public void DoWorkbookUpload(object in_instance) { var instance = in_instance as Google2uData; if (instance == null) { return; } if (!string.IsNullOrEmpty(instance.WorkbookUploadPath)) { try { // We need a DocumentService var service = new DocumentsService("Google2Unity"); var mimeType = Google2uMimeType.GetMimeType(instance.WorkbookUploadPath); var authenticator = new OAuth2Authenticator("Google2Unity", _authParameters); // Instantiate a DocumentEntry object to be inserted. var entry = new DocumentEntry { MediaSource = new MediaFileSource(instance.WorkbookUploadPath, mimeType) }; // Define the resumable upload link var createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); var link = new AtomLink(createUploadUrl.AbsoluteUri) { Rel = ResumableUploader.CreateMediaRelation }; entry.Links.Add(link); // Set the service to be used to parse the returned entry entry.Service = service; // Instantiate the ResumableUploader component. var uploader = new ResumableUploader(); // Set the handlers for the completion and progress events uploader.AsyncOperationCompleted += OnSpreadsheetUploadDone; uploader.AsyncOperationProgress += OnSpreadsheetUploadProgress; // Start the upload process uploader.InsertAsync(authenticator, entry, instance); } catch (Exception) { PushNotification( "There is a problem with your credentials. Clear the credentials and Re-Authorize G2U"); //instance.Messages.Add(new G2GUIMessage(GFGUIMessageType.InvalidLogin, ex.Message)); instance.Commands.Remove(GFCommand.WaitingForUpload); } } }
/// <summary> /// 文件流上传 /// </summary> /// <param name="key"></param> /// <param name="stream"></param> /// <returns></returns> public string StreamUpload(string key) { ResumableUploader resumableUploader = new ResumableUploader(ConfigUtil); HttpResult httpResult = resumableUploader.UploadStream(QiniuStream, key, TokenUtil, null); QiniuStream.Close(); return(httpResult.Text); }
/// <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); }
private bool UploadFileOverlay(string file, bool overLay = false) { // string filePath = LocalFile; if (uploadResult == null) { uploadResult = new StringBuilder(); } if (putPolicy != null) { string key = Path.GetFileName(file); System.IO.Stream fs = System.IO.File.OpenRead(file); if (overLay) { putPolicy.Scope = bucket + ":" + key; } else { putPolicy.Scope = bucket; } putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = qiNiuClientCfg.DeleteAfterDays; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); ResumableUploader target = new ResumableUploader(config); PutExtra extra = new PutExtra { ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(file, key) }; //设置断点续传进度记录文件 uploadResult.AppendLine("record file:" + extra.ResumeRecordFile); // extra.ResumeRecordFile = "test.progress"; //todo:未实现上传进度 HttpResult result = target.UploadStream(fs, key, token, extra); if (result.Code == 200) { uploadResult.AppendLine("上传成功! "); return(true); } else { string s = $"Code={result.Code},Text={result.Text}"; uploadResult.AppendLine("uploadResult:" + s); return(false); } } uploadResult.AppendLine("成员变量putPolicy为空!"); return(false); }
/// <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 OnGoogleNoteCreated(object sender, AsyncOperationCompletedEventArgs e) { DocumentEntry entry = e.Entry as DocumentEntry; Assert.IsNotNull(entry); Logger.Log("Created Google note", EventType.Information); //Now update the same entry //Instantiate the ResumableUploader component. ResumableUploader uploader = new ResumableUploader(); uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnGoogleNoteUpdated); uploader.UpdateAsync(_authenticator, entry, e.UserState); }
public static HttpResult UploadFile(Stream filestream, string fileName) { Mac mac = new Mac(_config.AccessKey, _config.SecretKey); PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = _config.Scope; putPolicy.SetExpires(3600); //putPolicy.DeleteAfterDays = 1; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Config config = new Config(); // 设置上传区域 switch (_config.Zone) { case QiniuConfiguration.UploadZone.CN_East: config.Zone = Zone.ZONE_CN_East; break; case QiniuConfiguration.UploadZone.CN_North: config.Zone = Zone.ZONE_CN_North; break; case QiniuConfiguration.UploadZone.CN_South: config.Zone = Zone.ZONE_CN_South; break; case QiniuConfiguration.UploadZone.US_North: config.Zone = Zone.ZONE_US_North; break; } // 设置 http 或者 https 上传 config.UseHttps = true; config.UseCdnDomains = true; config.ChunkSize = ChunkUnit.U512K; ResumableUploader target = new ResumableUploader(config); HttpResult result = target.UploadStream(filestream, fileName, token, null); if (result.Code != (int)HttpCode.OK) { Log.Error(result.Text); throw new Exception(result.Text); } return(result); }
/// <summary> /// 上传数据流,根据流长度以及设置的阈值(用户初始化UploadManager时可指定该值)自动选择表单或者分片上传 /// </summary> /// <param name="stream">待上传的数据流,要求:流长度(Stream.Length)是确定的</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传数据后的返回结果</returns> public HttpResult UploadStream(Stream stream, string saveKey, string token) { HttpResult result = new HttpResult(); if (stream.Length > PUT_THRESHOLD) { ResumableUploader ru = new ResumableUploader(UPLOAD_FROM_CDN); result = ru.UploadStream(stream, saveKey, token, null); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = fu.UploadStream(stream, saveKey, token); } return(result); }
/// <summary> /// [异步async]上传数据 /// </summary> /// <param name="data">待上传的数据</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传文件后的返回结果</returns> public async Task <HttpResult> UploadDataAsync(byte[] data, string saveKey, string token) { HttpResult result = new HttpResult(); if (data.Length > PUT_THRESHOLD) { ResumableUploader ru = new ResumableUploader(UPLOAD_FROM_CDN); result = await ru.UploadDataAsync(data, saveKey, token, upph); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = await fu.UploadDataAsync(data, saveKey, token); } return(result); }
/// <summary> /// [异步async]上传数据流,根据流长度以及设置的阈值(用户初始化UploadManager时可指定该值)自动选择表单或者分片上传 /// </summary> /// <param name="stream">待上传的数据流,要求:流长度(Stream.Length)是确定的</param> /// <param name="saveKey">要保存的文件名称</param> /// <param name="token">上传凭证</param> /// <returns>上传数据后的返回结果</returns> public async Task <HttpResult> UploadStreamAsync(Stream stream, string saveKey, string token) { HttpResult result = new HttpResult(); if (stream.Length > PUT_THRESHOLD) { ResumableUploader ru = new ResumableUploader(UPLOAD_FROM_CDN); result = await ru.UploadStreamAsync(stream, saveKey, token, sph); } else { FormUploader fu = new FormUploader(UPLOAD_FROM_CDN); result = await fu.UploadStreamAsync(stream, saveKey, token); } return(result); }
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 async Task UploadFileTest() { Mac mac = new Mac(AccessKey, SecretKey); string key = FileKey2; StorageFile localFile = await StorageFile.GetFileFromPathAsync(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 = await target.UploadFileAsync(localFile, key, token); Assert.AreEqual((int)HttpCode.OK, result.Code); }
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); }
protected override async Task UploadFileAsync(FileInfo fileInfo, int?expireIn = null, CancellationToken cancellationToken = default) { Mac mac = new Mac(Options.AccessKey, Options.SecretKey); PutPolicy putPolicy = new PutPolicy { Scope = fileInfo.Directory + ":" + fileInfo.Name, CallbackBody = Options.UploadCallbackBody, CallbackBodyType = Options.UploadCallbackBodyType, CallbackHost = Options.UploadCallbackHost, CallbackUrl = Options.UploadCallbackUrl }; if (expireIn.HasValue) { putPolicy.SetExpires(expireIn.Value); } if (Options.DeleteAfterDays > 0) { putPolicy.DeleteAfterDays = Options.DeleteAfterDays; } string jstr = putPolicy.ToJsonString(); string token = Auth.CreateUploadToken(mac, jstr); UploadProgressHandler handler = (uploadByte, totalByte) => { OnFileUploadProgressChanged(uploadByte, totalByte); }; // 带进度的上传 ResumableUploader uploader = new ResumableUploader(); var httpResult = await uploader.UploadDataAsync(fileInfo.Data, fileInfo.Name, token, handler); // 普通上传 //FormUploader fu = new FormUploader(); //var httpResult = await fu.UploadDataAsync(fileInfo.Data, fileInfo.Name, token); // TODO: 处理响应代码 Console.WriteLine(httpResult.Code); }
public string Sling(string path) { string token = Guid.NewGuid().ToString("N"); zipPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip(); fz.CreateZip(zipPath, path, true, "", ""); int CHUNK_SIZE = 10485760; ClientLoginAuthenticator cla = new ClientLoginAuthenticator("commanigy-slingshot-v1", ServiceNames.Documents, "username", "password"); // Set up resumable uploader and notifications ResumableUploader ru = new ResumableUploader(CHUNK_SIZE); ru.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(this.OnDone); ru.AsyncOperationProgress += new AsyncOperationProgressEventHandler(this.OnProgress); // Set metadata for our upload. Document entry = new Document(); entry.Title = string.Format("testupload", token); //entry.MediaSource = new MediaFileSource(new FileStream(zipPath, FileMode.Open), "test.zip", "application/zip"); //entry.MediaSource = new MediaFileSource(zipPath, "application/zip"); entry.MediaSource = new MediaFileSource(zipPath, "application/zip"); // Add the upload uri to document entry. Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri); link.Rel = ResumableUploader.CreateMediaRelation; entry.DocumentEntry.Links.Add(link); string userObject = "Just a sample text"; ru.InsertAsync(cla, entry.DocumentEntry, userObject); //ru.InsertAsync(cla, createUploadUrl, new FileStream(zipPath, FileMode.Open), "application/zip", "mytest.zip", userObject); return(token); }
/// <summary> /// 断点续传 /// </summary> /// <param name="localFile"></param> /// <returns></returns> public string ResumeUploadFile(string localFile) { if (!File.Exists(localFile)) { return("文件不存在"); } var filename = Path.GetFileName(localFile); //文件名 var extension = Path.GetExtension(localFile); //扩展名 var mac = new Mac(AccessKey, SecretKey); var rand = new Random(); string key = $"jnkj_{rand.Next()}{extension}"; Stream fs = File.OpenRead(localFile); var putPolicy = new PutPolicy { Scope = Bucket + ":" + key }; putPolicy.SetExpires(3600); putPolicy.DeleteAfterDays = 1; var token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); var config = new Config { UseHttps = true, Zone = Zone.ZONE_CN_East, UseCdnDomains = true, ChunkSize = ChunkUnit.U512K }; var target = new ResumableUploader(config); var extra = new PutExtra { ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(localFile, key) }; //设置断点续传进度记录文件 Console.WriteLine("record file:" + extra.ResumeRecordFile); extra.ResumeRecordFile = "test.progress"; var result = target.UploadStream(fs, key, token, extra); Console.WriteLine("resume upload: " + result); return(result.ToString()); }
public async Task ResumeUploadFileTest() { var mac = new Mac(AccessKey, SecretKey); var rand = new Random(); var key = $"UploadFileTest_{rand.Next()}.dat"; var filePath = LocalFile; Stream fs = File.OpenRead(filePath); var putPolicy = new PutPolicy { Scope = Bucket + ":" + key, DeleteAfterDays = 1 }; putPolicy.SetExpires(3600); var token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); var config = new Config { UseHttps = true, Zone = Zone.ZoneCnEast, UseCdnDomains = true, ChunkSize = ChunkUnit.U512K }; var target = new ResumableUploader(config); //设置断点续传进度记录文件 var extra = new PutExtra { ResumeRecordFile = ResumeHelper.GetDefaultRecordKey(filePath, key) }; Console.WriteLine("record file:" + extra.ResumeRecordFile); extra.ResumeRecordFile = "test.progress"; var result = await target.UploadStream(fs, key, token, extra); Console.WriteLine("resume upload: " + result); Assert.Equal((int)HttpCode.OK, result.Code); }