I have a lot of images in the Media section of the CMS. I was wondering what the best way to get a list of the images and their file sizes were?
Would manipulating the xml string in the db be better or adding a column in the CMS front end?
I have a lot of images in the Media section of the CMS. I was wondering what the best way to get a list of the images and their file sizes were?
Would manipulating the xml string in the db be better or adding a column in the CMS front end?
UPDATED ANSWER:
Faster and better recursive solution:
<ul id="imageList">
@foreach (var item in Umbraco.TypedMediaAtRoot()) {
@ShowMediaItems(item)
}
</ul>
@helper ShowMediaItems(IPublishedContent media) {
if (media.Descendants().Any(p => p.DocumentTypeAlias != "Folder") && media.DocumentTypeAlias == "Folder") {
<ul>
@foreach (var child in media.Children) {
@ShowMediaItems(child)
}
</ul>
} else if (media.DocumentTypeAlias == "Image") {
<li>Image url: @media.Url - Size: @(media.GetPropertyValue<int>("umbracoBytes"))</li>
}
}
It will go as deep as it has to and is much faster. I've put a new ul list for each level, but you can get rid of it.
ORIGINAL ANSWER:
This works and it will be slow when dealing with a lot of images but if you need to get a list for yourself (as in a one time thing), then it should do the job:
<ul>
@foreach (var item in Umbraco.TypedMediaAtRoot())
{
//Level 1
if (item.DocumentTypeAlias == "Folder")
{
//Level 2
foreach (var item2 in Umbraco.TypedMedia(item.Id).Children)
{
if (item2.DocumentTypeAlias == "Folder")
{
//Level 3
foreach (var item3 in Umbraco.TypedMedia(item2.Id).Children)
{
if (item3.DocumentTypeAlias == "Folder")
{
//Level 3
//etc..
}
else if (item3.DocumentTypeAlias == "Image")
{
<li>Image url: @item3.Url - Size: @(item3.GetPropertyValue<int>("umbracoBytes"))</li>
}
}
}
else if (item2.DocumentTypeAlias == "Image")
{
<li>Image url: @item2.Url - Size: @(item2.GetPropertyValue<int>("umbracoBytes"))</li>
}
}
}
else if (item.DocumentTypeAlias == "Image")
{
<li>Image url: @item.Url - Size: @(item.GetPropertyValue<int>("umbracoBytes"))</li>
}
}
</ul>
You can go as deep as you prefer depending on how many folders you've got in your media section.
See comments in the code. Level 1 is the root media folder, Level 2 is a folder that is under the root and so on.
I've just tested it on my local Umbraco instance and it works.
Regarding the sizes, they come as bytes, so you can do your own calculation using the GetPropertyValue("umbracoBytes")