The MediaService acts as a "gateway" to Umbraco data for operations which are related to media.
Browse the API documentation for IMediaService interface.
Namespace: Umbraco.Cms.Core.Services
Assembly: Umbraco.Core.dll
All samples in this document will require reference to the following packages:
Samples in this document will require the following using statements:
If you wish to use the media service in a class, you need to specify the IMediaService
interface in your constructor:
In Razor views, you can access the media service through the @inject
directive:
To create a new folder at the root of the media archive, your code could look like the following:
Alternatively, you can replace the Constants in the above sample with hardcoded values.
For the CreateMedia
method, the first parameter is the name of the folder to be created.
The second parameter is the ID of the parent media item. Constants.System.Root
is a constant defined in Umbraco with the value of -1
, which is used for indicating the root of the media archive. Instead of specifying the numeric ID of the parent, you may instead specify either a Guid
ID or an IMedia
instance representing the parent media.
The third parameter is the alias of the Media Type. As Umbraco comes with a Folder Type by default, we can use the Constants.Conventions.MediaTypes.Folder
constant to specify that the alias of the Media Type is Folder
.
Besides the three mandatory parameters, you can specify a user's numeric ID for media creation attribution. Unspecified cases default to the "Administrator" user with ID -1
.
You can specify a Stream
for the contents of the file that should be created.
As an example, if you have an image on disk named unicorn.jpg
in the images folder of wwwroot
. You can open a new stream for a file on the disk, and then create a new media item for that file in Umbraco:
Please be aware that you will need to inject the following services:
MediaFileManager _mediaFileManager
IShortStringHelper _shortStringHelper
IContentTypeBaseServiceProvider _contentTypeBaseServiceProvider
MediaUrlGeneratorCollection _mediaUrlGeneratorCollection
IMediaService _mediaService
IWebHostEnvironment _webHostEnvironment
Again Umbraco will make sure the necessary properties are updated.