Umbraco Create New Media in Postback

January 08, 2016

Umbraco's Back Office makes it easy to manage and create media, but there may be a case where you want the end user to be able to upload files, images, etc. This can be done similarly to uploading other content nodes.

From within a SurfaceController, you'll have access to the powerful MediaService which will allow you to CreateMedia. The parameters to this function is the filename, the parent node, and the name of the node that will show up in the Back Office. Next you'll want to set properties on the instance of the Media Type. If you want to add additional properties, you can edit the elements that appear within Umbraco Back Office -> Settings -> Media Types

public class ImageGallerySurfaceController : SurfaceController {
public ActionResult Index(int galleryId) {
var gallery = new ImageGalleryFormViewModel  { GalleryId = galleryId} ;
return PartialView("ImageGalleryForm", gallery);
}
// This can be called within a template with
// @Html.Action("ImageGallerySurface", "Index")
[HttpPost]
public ActionResult PostImages(CommentsModel model) {
if(!ModelState.IsValid) return CurrentUmbracoPage();
foreach(var file in model.Files) {
var mediaObject = Services.MediaService.CreateContent(file.FileName, CurrentPage.Id, "Comment Name");
mediaObject.SetValue("umbracoFile", file);
Services.MediaService.Save(newComment); // or SaveAndPublish(node)
}
TempData["success"] = true;
return RedirectToCurrentUmbracoPage();
}

public class ImageGalleryFormViewModel
{
[Required]
   public int GalleryId {get; set;
public IEnumerable<HttpPostedFileBase> Files {get; set;}
}

Share

Comments