private JsonResult UploadCurrentChunk(CloudFile model, byte[] chunk, int id) { using (var chunkStream = new MemoryStream(chunk)) { var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes( string.Format(CultureInfo.InvariantCulture, "{0:D4}", id))); try { model.BlockBlob.PutBlock( blockId, chunkStream, null, null, new BlobRequestOptions() { RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(10), 3) }, null); return null; } catch (StorageException e) { Session.Remove("CurrentFile"); model.IsUploadCompleted = true; model.UploadStatusMessage = "Failed to Upload file. Exception - " + e.Message; return Json(new { error = true, isLastBlock = false, message = model.UploadStatusMessage }); } } }
private ActionResult CommitAllChunks(CloudFile model) { model.IsUploadCompleted = true; bool errorInOperation = false; try { var blockList = Enumerable.Range(1, (int)model.BlockCount).ToList<int>().ConvertAll(rangeElement => Convert.ToBase64String(Encoding.UTF8.GetBytes( string.Format(CultureInfo.InvariantCulture, "{0:D4}", rangeElement)))); model.BlockBlob.PutBlockList(blockList); var duration = DateTime.Now - model.StartTime; float fileSizeInKb = model.Size / 1024; string fileSizeMessage = fileSizeInKb > 1024 ? string.Concat((fileSizeInKb / 1024).ToString(CultureInfo.CurrentCulture), " MB") : string.Concat(fileSizeInKb.ToString(CultureInfo.CurrentCulture), " KB"); model.UploadStatusMessage = string.Format(CultureInfo.CurrentCulture, "File uploaded successfully. {0} took {1} seconds to upload", fileSizeMessage, duration.TotalSeconds); CreateMediaAsset(model); } catch (StorageException e) { model.UploadStatusMessage = "Failed to Upload file. Exception - " + e.Message; errorInOperation = true; } finally { Session.Remove("CurrentFile"); } return Json(new { error = errorInOperation, isLastBlock = model.IsUploadCompleted, message = model.UploadStatusMessage, assetId = model.AssetId }); }
private void CreateMediaAsset(CloudFile model) { string mediaAccountName = ConfigurationManager.AppSettings["MediaAccountName"]; string mediaAccountKey = ConfigurationManager.AppSettings["MediaAccountKey"]; string storageAccountName = ConfigurationManager.AppSettings["StorageAccountName"]; string storageAccountKey = ConfigurationManager.AppSettings["StorageAccountKey"]; CloudMediaContext context = new CloudMediaContext(mediaAccountName, mediaAccountKey); var storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, storageAccountKey), true); var cloudBlobClient = storageAccount.CreateCloudBlobClient(); var mediaBlobContainer = cloudBlobClient.GetContainerReference(cloudBlobClient.BaseUri + "temporary-media"); mediaBlobContainer.CreateIfNotExists(); // Create a new asset. IAsset asset = context.Assets.Create("NewAsset_" + Guid.NewGuid(), AssetCreationOptions.None); IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy", TimeSpan.FromMinutes(120), AccessPermissions.Write); ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy); // Get the asset container URI and copy blobs from mediaContainer to assetContainer. Uri uploadUri = new Uri(destinationLocator.Path); string assetContainerName = uploadUri.Segments[1]; CloudBlobContainer assetContainer = cloudBlobClient.GetContainerReference(assetContainerName); string fileName = HttpUtility.UrlDecode(Path.GetFileName(model.BlockBlob.Uri.AbsoluteUri)); var sourceCloudBlob = mediaBlobContainer.GetBlockBlobReference(fileName); sourceCloudBlob.FetchAttributes(); if (sourceCloudBlob.Properties.Length > 0) { IAssetFile assetFile = asset.AssetFiles.Create(fileName); var destinationBlob = assetContainer.GetBlockBlobReference(fileName); destinationBlob.DeleteIfExists(); destinationBlob.StartCopyFromBlob(sourceCloudBlob); destinationBlob.FetchAttributes(); if (sourceCloudBlob.Properties.Length != destinationBlob.Properties.Length) model.UploadStatusMessage += "Failed to copy as Media Asset!"; } destinationLocator.Delete(); writePolicy.Delete(); // Refresh the asset. asset = context.Assets.Where(a => a.Id == asset.Id).FirstOrDefault(); var ismAssetFiles = asset.AssetFiles.ToList(). Where(f => f.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)) .ToArray(); if (ismAssetFiles.Count() != 1) throw new ArgumentException("The asset should have only one, .ism file"); ismAssetFiles.First().IsPrimary = true; ismAssetFiles.First().Update(); model.UploadStatusMessage += " Created Media Asset '" + asset.Name + "' successfully."; model.AssetId = asset.Id; }
public ActionResult SetMetadata(int blocksCount, string fileName, long fileSize) { var container = CloudStorageAccount.Parse( ConfigurationManager.AppSettings["StorageConnectionString"]).CreateCloudBlobClient() .GetContainerReference(ConfigurationManager.AppSettings["StorageContainerReference"]); container.CreateIfNotExists(); var fileToUpload = new CloudFile() { BlockCount = blocksCount, FileName = fileName, Size = fileSize, BlockBlob = container.GetBlockBlobReference(fileName), StartTime = DateTime.Now, IsUploadCompleted = false, UploadStatusMessage = string.Empty }; Session.Add("CurrentFile", fileToUpload); return Json(true); }