public async Task <UploadFileResponse> UploadFile(string fileName = null, string content = null, string sha1 = null) { var u = await GetUploadUrl(); if (fileName == null) { fileName = RandomString.Next(10); } if (content == null) { content = RandomString.Next(10); } if (sha1 == null) { sha1 = content.Sha1(); } var contentBytes = Encoding.UTF8.GetBytes(content); return(await api.UploadFile( u.uploadUrl, u.authorizationToken, fileName, "application/octet-stream", contentBytes.Length, sha1, new Dictionary <string, string> { { "asdf", "qwer" } }, new MemoryStream(contentBytes))); }
public async Task UploadFile(string sourcePath, string destinationPath, string contentType = "text/plain", IProgress <StreamProgress> checksumProgress = null, IProgress <StreamProgress> uploadProgress = null) { // Ensure the file cannot be altered whilst being uploaded. using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var qs = new ProgressReportingStream(fs)) { // The B2 HTTP api requires the SHA1 checksum before uploading; this means the file must be // read twice, doh! var e = new B2UrlEncoder(); var shaTask = Task.Run(() => SHA1.Create().ComputeHash(qs)); if (checksumProgress != null) { while (await Task.WhenAny(shaTask, Task.Delay(100)) != shaTask) { checksumProgress.Report(qs.Progress()); } } await shaTask; if (checksumProgress != null) { checksumProgress.Report(qs.Progress()); } var sha1hex = new StringBuilder(40); foreach (var b in shaTask.Result) { sha1hex.AppendFormat("{0:X2}", b); } qs.Position = 0; var getUploadUrlResponse = await b2api.GetUploadUrl(ApiUrl, AuthorizationToken, BucketId).ConfigureAwait(false); var url = getUploadUrlResponse.uploadUrl; var attributes = new Dictionary <string, string>(); var fileInfo = new FileInfo(sourcePath); attributes["last_modified_millis"] = fileInfo.LastWriteTimeUtc.ToUnixTimeMillis().ToString(); var uploadFileTask = b2api.UploadFile(url, getUploadUrlResponse.authorizationToken, destinationPath, contentType, fileInfo.Length, sha1hex.ToString(), attributes, qs); if (uploadProgress != null) { while (await Task.WhenAny(uploadFileTask, Task.Delay(100)) != uploadFileTask) { uploadProgress.Report(qs.Progress()); } } await uploadFileTask; if (uploadProgress != null) { uploadProgress.Report(qs.Progress()); } } }