Media Files

Last Updated: 2018-10-30

By default Piranha allows the follow files to be uploaded into the Media library.

  • .jpg, .jpeg & .png images
  • .mp4 videos
  • .pdf documents

The reason for such a restrictive upload policy is simply that these are the types of files that are supported on most devices, included the different mobile devices out there.

Referencing Media

Media files can be easily referenced in your content types by using any of the available media fields. The following example shows a Page Type referencing an image, a video, and a list of media objects of any type.

using System.Collections.Generic;
using Piranha.Models;
using Piranha.Extend.Fields;

public class MediaPage : Page<MediaPage>
{
[Region]
public ImageField Image { get; set; }

[Region]
public VideoField Video { get; set; }

[Region]
public IList<MediaField> Assets { get; set; }
}

Querying Media

All methods for accessing media files can be found in the current IApi in the MediaRepository. This following code would get all available media assets in the root folder in the media library.

using System.Collections.Generic;
using Piranha;
using Piranha.Media;

public IList<Media> GetMediaInRootFolder(IApi api)
{
return api.Media.GetAll();
}

Uploading Media

Media files can be uploaded easily from a Stream or a Byte Array by using the current IApi.

Upload media from a stream

using System.IO;
using Piranha.Models;

using (var stream = File.OpenRead("myimage.png"))
{
api.Media.Save(new StreamMediaContent
{
Filename = "myimage.png",
Data = stream
});
}

Uploading media from a byte array

using Piranha.Models;

api.Media.Save(new BinaryMediaContent
{
Filename = "myimage.png",
Data = myByteArray
});

Adding Media Types

If you need to handle more media types in your application you can easily register them in your application startup after the Piranha.App has been initialized. The following code will for example allow .gif images.

Piranha.App.MediaTypes.Images.Add(".gif", "image/gif");

It's very import to classify the media types your add correctly in terms of what type it is (document, image or video). This is so that Piranha knows what to do with the file.