How to add a media item via the API

This sample illustrates how to add a media block type to the CMS. This assumes you have a Article page type but really you just need to pass in a ContentLink to the location you want to save the file to. 

Below are some sample methods to add a new blob and insert data into it. 

//article is a page type (used to get the content link)
    public string AddFile(Article article, HtmlFile file)
    {
        string url = "";
        try
        {
            var contentAssetHelper = ServiceLocator.Current.GetInstance<ContentAssetHelper>();
            // get an existing content asset folder or create a new one
            var assetsFolder = contentAssetHelper.GetOrCreateAssetFolder(article.ContentLink);
            var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
            var blobFactory = ServiceLocator.Current.GetInstance<EPiServer.Framework.Blobs.BlobFactory>();
            string name = "";
            string ext = "";
            var file = new MediaData();
            if (file.Image)
            {
                //add an image
                file = contentRepository.GetDefault<Project.Models.Media.ImageFile>(assetsFolder.ContentLink);
                name = file.Name;
                ext = file.Ext;
            }
            else
            {
                //add a file
                file = contentRepository.GetDefault<Project.Models.Media.GenericMedia>(assetsFolder.ContentLink);
                name = file.Name;
                ext = file.Ext;
            }
            file.Name = name;
            //create blob storage
            var blob = blobFactory.CreateBlob(file.BinaryDataContainer, "." + ext.TrimStart('.'));
            //get the data for the url provided
            var data = GetByteData(file.Url);
            //write data to blob
            blob.Write(new System.IO.MemoryStream(data));
            file.BinaryData = blob;
            //save the file
            //take note of the no access level. You may not want to use this in a production situation. 
            var fileRef = contentRepository.Save(file, EPiServer.DataAccess.SaveAction.Publish, AccessLevel.NoAccess);
            //get the url of the file 
            return EPiServer.Web.Routing.UrlResolver.Current.GetUrl(fileRef);
        }
        catch (Exception ex)
        {
        }
        return url;
    }

    /// <summary>
    /// Get the file data
    /// </summary>
    /// <param name="url">URL to retrieve the data from</param>
    /// <returns>returns the file byte array</returns>
    private byte[] GetByteData(string url)
    {
        try
        {
            using (var client = new System.Net.WebClient())
            {
                byte[] data = client.DownloadData(new Uri(url));
                return data;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }