/// <summary> /// Save or update media assets to storage /// </summary> /// <param name="model">Upload model</param> /// <returns>The number of upload managed to be saved or updated</returns> public async Task <int> SaveMedia(MediaUploadModel model) { var uploaded = 0; // Go through all of the uploaded files foreach (var upload in model.Uploads) { if (upload.Length > 0 && !string.IsNullOrWhiteSpace(upload.ContentType)) { using (var stream = upload.OpenReadStream()) { await _api.Media.SaveAsync(new StreamMediaContent { Id = model.Uploads.Count() == 1 ? model.Id : null, FolderId = model.ParentId, Filename = Path.GetFileName(upload.FileName), Data = stream }); uploaded++; } } } return(uploaded); }
public IActionResult UploadProfilePicture(MediaUploadModel mediaModel) { if (!_userSettings.AreProfilePicturesEnabled) { return(NotFound()); } var mediaFile = mediaModel.MediaFile; if (mediaFile == null || mediaFile.Length == 0) { return(R.Fail.Result); } var media = _mediaAccountant.GetMediaInstance(mediaFile, 0); //save it _mediaService.Insert(media); _userService.Update(new { ProfilePictureId = media.Id }, x => x.Id == CurrentUser.Id, null); var model = _modelMapper.Map <MediaModel>(media); model.ThumbnailUrl = _mediaAccountant.GetPictureUrl(media, ApplicationEngine.ActiveTheme.UserProfileImageSize, true); model.ImageUrl = _mediaAccountant.GetPictureUrl(media); return(R.Success.With("media", model).Result); }
public async Task <ActionResult> UploadMedia([FromForm] MediaUploadModel model) { if (model.File == null || model.File.Length == 0) { return(Content("Chưa chọn file để tải lên")); } var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "upload", model.File.FileName); var filename = Path.GetFileNameWithoutExtension(path); var extension = Path.GetExtension(path); var newFileName = $"{filename}-{Common.RandomString(6)}"; var entity = new Media { Id = ObjectId.GenerateNewId(), Type = (int)model.Entity.Type, Title = newFileName, FileName = $"{newFileName}{extension}", FileSize = model.File.Length / 1024, FileType = model.File.ContentType }; var response = await _mediaService.SaveAsync(new SaveRequest <Media> { Entity = entity, UserId = _sessionHelper.CurrentUserId }); if (response.Success) { path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "upload", entity.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await model.File.CopyToAsync(stream); //get image size var image = System.Drawing.Image.FromStream(stream); if (image != null) { entity.Width = image.Width; entity.Height = image.Height; await _mediaService.SaveAsync(new SaveRequest <Media> { Entity = entity, IsEdit = true, UserId = _sessionHelper.CurrentUserId }); } } } return(RedirectToAction("Media")); }
public IActionResult UploadMedia(MediaUploadModel mediaModel) { var mediaFile = mediaModel.MediaFile; if (mediaFile == null || mediaFile.Length == 0) { return(R.Fail.Result); } var media = _mediaAccountant.GetMediaInstance(mediaFile, 0); //save it _mediaService.Insert(media); //link media if we can if (mediaModel.EntityId > 0) { switch (mediaModel.EntityName) { case "product": if (_productService.Count(x => x.Id == mediaModel.EntityId) > 0) { _productService.LinkMediaWithProduct(media.Id, mediaModel.EntityId); } break; case "category": if (_categoryService.Count(x => x.Id == mediaModel.EntityId) > 0) { _categoryService.Update(new { MediaId = media.Id }, x => x.Id == mediaModel.EntityId, null); } break; case "user": if (_userService.Count(x => x.Id == mediaModel.EntityId) > 0) { _userService.Update(new { ProfilePictureId = media.Id }, x => x.Id == mediaModel.EntityId, null); } break; } } //model var model = _modelMapper.Map <MediaModel>(media); model.ThumbnailUrl = _mediaAccountant.GetPictureUrl(media, ApplicationConfig.AdminThumbnailWidth, ApplicationConfig.AdminThumbnailHeight); model.ImageUrl = _mediaAccountant.GetPictureUrl(media); return(R.Success.With("media", model).Result); }
public async Task <IActionResult> Upload([FromForm] MediaUploadModel model) { // Allow for dropzone uploads if (!model.Uploads.Any()) { model.Uploads = HttpContext.Request.Form.Files; } try { var uploaded = await _service.SaveMedia(model); if (uploaded == model.Uploads.Count()) { return(Ok(new StatusMessage { Type = StatusMessage.Success, Body = $"Uploaded all media assets" })); } else if (uploaded == 0) { return(Ok(new StatusMessage { Type = StatusMessage.Error, Body = $"Could not upload the media assets." })); } else { return(Ok(new StatusMessage { Type = StatusMessage.Information, Body = $"Uploaded {uploaded} of {model.Uploads.Count()} media assets." })); } } catch (Exception e) { return(BadRequest(new StatusMessage { Type = StatusMessage.Error, Body = e.Message })); } }
/// <summary> /// Upload the blob and then (if nothing went wrong) drop a message on the queue announcing the blob /// </summary> /// <param name="queueValet"></param> /// <param name="mediaByteStream">Might be from File Upload via web page</param> /// <param name="origFilename"></param> /// <param name="mimeType"></param> /// <param name="byteCount">Count of bytes in the stream. Not used at this time. May be used in future to optimize the upload to blob storage, for telemetry, or to block uploads over a certain size.</param> /// <param name="destinationUrl"></param> /// <param name="blobValet"></param> public static void CaptureUploadedMedia(BlobValet blobValet, QueueValet queueValet, Stream mediaByteStream, string origFilename, string mimeType, int byteCount, string destinationUrl) { try { // TODO: obviate MediaStorageUrlFile.ExtTemplate by basing on MediaStorageValetKeyUrl value --- value="http://127.0.0.1:10000/devstoreaccount1/popmedia/{0}{1}" & "http://127.0.0.1:10000/devstoreaccount1/popmedia?sr=c&si=open-wide-container-access-policy&sig=X0yGw1Ydmu%2BCwk%2FTY7nj5HFgzv%2BIYg%2Bun%2BHQhNMmThk%3D" #if false var destinationUrl = String.Format(ConfigurationManager.AppSettings["MediaStorageUrlFile.ExtTemplate"], Guid.NewGuid(), new FileInfo(origFilename).Extension ); var valetKeyUrl = ConfigurationManager.AppSettings["MediaStorageValetKeyUrl"]; // if that worked, notify via queue var mediaIngestionQueueValetKeyUrl = ConfigurationManager.AppSettings["MediaIngestionQueueValetKeyUrl"]; #endif blobValet.UploadStream(new Uri(destinationUrl), mediaByteStream, mimeType); // TODO: at moment is sync (not async) to avoid race condition mentioned below var info = new MediaUploadModel { BlobUrl = destinationUrl, Username = "******" }; // prep an arbitrary object to send on the queue, not just a string (not rich enough for our use case) var queueMessage = new CloudQueueMessage(ByteArraySerializer <MediaUploadModel> .Serialize(info)); // TODO: race condition when both uploading a BLOB and posting the Queue message - the queue message processing // TODO: ... can begin before the blob upload is complete -- need to sync these // TODO: ... BUT! for now it will still FUNCTION CORRECTLY (if inefficiently) due to Queue-Centric Workflow Pattern retries IF not determined to be a Poison Message // There is no real need for a 50ms delay before the message can appear in queue, but just showing how to do it. // Technique is sometimes useful when there's a reason to delay its processing. You could use it to implement a // scheduler, for example. In the case of PoP, there are no obvious use cases. A made-up use case might be if PoP // introduced a way to make photos show up in the future allowing the user uploading them to indicate PoP should // delay processing for, say, up to 24 hours, and let the user optionally specify a delay within that range. queueValet.AddMessage(queueMessage, initialVisibilityDelay: TimeSpan.FromMilliseconds(50)); } catch (StorageException ex) { System.Diagnostics.Trace.TraceError("Exception thrown in BlobExtensions.UploadFile: " + ex); throw; } }