Watch video

Creating media

One of the most important components when creating media programmatically in your Umbraco project is the Media Service.

It is one of the many services that Umbraco CMS ships with, and it will allow you to interact with the Media API directly from your surface controller.

Learn more about the Media service and Umbraco Services in the general by following the links below in the "Resources" section.

The 3 steps of adding images programmatically to a Umbraco website

When adding images programmatically to your Umbraco website, you will need to go through the following three steps:

  1. Create the media item. This is where you choose the Image Media Type. This will, as a start, create an empty Image media item in your project.
  2. To populate the media item, you need to use the SetValue() method from the Media Service.
  3. Add the now populated media item to the content node using the SetValue() method from the Content Service.

Media Types

When talking about media in a Umbraco project it could be one of three different things:

  • Folder
  • File
  • Image

In this video, you will be working with two of those types as you will be creating a folder and an image.

To create either of these three types, you will be using the CreateMedia() method. This method takes three parameters:

  • The name of the new media item.
  • The ID of the folder where the media item should be placed into - should it be placed in the root of the Media tree, then the parent ID should be '-1'.
  • The alias of the Media Type that should be used to create the new item - so, should it be an Image, a File, or a Folder?

SetValue() method

In the previous video, you used the SetValue() method from the Content Service to populate properties on your new content node.

The Media Service has a similar method - it's using the same name, but takes four parameters instead of three:

  • The "ContentTypeBaseService" is used to set the ContentType - in this case, the Image Media Type.
  • The "UmbracoFile" property, which will ensure that the image gets the correct default properties, like the dimensions of the image.
  • The name of the uploaded image.
  • The input stream.




Check out the resources below to learn more about MVC and MVC in Umbraco.

Use the bottom below to download an updated version of the ArticleFormController.cs file including comments.

Project login details

Password: 1234567890

Get the source code!

Surface Controllers

Total Time: 01:18:05

In the Surface Controllers chapter, you will learn more about some of the key functionality in Umbraco and how you can use MVC to programmatically add content and media to your Umbraco website.