Skip to content

Instantly share code, notes, and snippets.

@FransdeJong
Created June 29, 2021 08:41
Show Gist options
  • Save FransdeJong/1b80db38ef58191b1bc5892f2364990d to your computer and use it in GitHub Desktop.
Save FransdeJong/1b80db38ef58191b1bc5892f2364990d to your computer and use it in GitHub Desktop.
Serve Umbraco image property with static Url
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Composing;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Umbraco.Web.PublishedModels;
namespace Site.Core.Controllers
{
public class ImagesController : SurfaceController
{
private FileContentResult getFileContentResult(IPublishedContent media)
{
var umbracoFile = media.HasProperty("umbracoFile") && media.HasValue("umbracoFile") ? media.Value<string>("umbracoFile") : null;
var umbracoFileObject = JObject.Parse(umbracoFile);
var src = umbracoFileObject.GetValue("src") != null ? umbracoFileObject.GetValue("src").ToString() : null;
var fileExtension = media.Value<string>("umbracoExtension");
if (src != null)
{
using (var fileStream = Current.MediaFileSystem.OpenFile(src))
{
byte[] fileBytes = null;
using (var memoryStream = new System.IO.MemoryStream())
{
fileStream.CopyTo(memoryStream);
fileBytes = memoryStream.ToArray();
}
return File(fileBytes, MimeMapping.GetMimeMapping("image/" + fileExtension), media.Name + "." + fileExtension);
}
}
return null;
}
public FileContentResult Emailheader()
{
var homepage = Umbraco.ContentAtRoot().FirstOrDefault(x => x.ContentType.Alias == Homepage.ModelTypeAlias) as Homepage;
var headerImage = homepage.Emailheader;
if (headerImage != null)
{
var publishedMedia = headerImage.MediaItem;
getFileContentResult(publishedMedia);
}
return null;
}
public FileContentResult Emailfooter()
{
var homepage = Umbraco.ContentAtRoot().FirstOrDefault(x => x.ContentType.Alias == Homepage.ModelTypeAlias) as Homepage;
var footerImage = homepage.Emailfooter;
if (footerImage != null)
{
var publishedMedia = footerImage.MediaItem;
getFileContentResult(publishedMedia);
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment