Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • g3t 32 posts 144 karma points
    Sep 21, 2017 @ 11:44
    g3t
    0

    Export media folder

    Is there a tool or some technique to extract all file from a media folder that works in 7.4 . Tried Export media package but no luck in version 7 and above. thanks

  • Alex Skrypnyk 6175 posts 24186 karma points MVP 8x admin c-trib
    Sep 21, 2017 @ 11:47
    Alex Skrypnyk
    0

    Hi g3t

    Where do you want to export media files? Why?

    Thanks,

    Alex

  • g3t 32 posts 144 karma points
    Sep 21, 2017 @ 13:37
    g3t
    1

    Hi Alex

    Would be great to be able to collect and export a folder as zip like the Export Media package.

    But any way that would allow downloading the whole folder instead of having to click the media link in the properties tab for each media item to download it.

    Its really for extra archiving purposes. I'm not able to upgrade from SQL CE for a while yet.

    thanks

  • Ben 5 posts 120 karma points
    Jun 07, 2018 @ 11:11
    Ben
    1

    Hey,

    here is how i do it most of the time;

    add this code to a cshtml file of yours, the 9126 is the id of the parent media item (usually a folder)

    @{
        var folder = Umbraco.TypedMedia(9126);
        var mediaItems = folder.Descendants();
    }
    
    @if (mediaItems.Any())
    {
    <ul>
    
        @foreach (var media in mediaItems)
        {
            <li>
                <a href="@media.Url">@media.Name</a>
            </li>
        }
    </ul>
    }
    

    now navigate to that page, where you added the snipped

    use a chrome extension, called "fatkun image downloader". That tool will render all image links to a new page, and then you can simple use the save image button, you can even filter on extension

    sample screen of the chrome extesion

  • Andy Neil 7 posts 80 karma points c-trib
    Jun 07, 2018 @ 13:15
    Andy Neil
    1

    Hi There,

    Here's some code that will give you all the media listed as a CSV, but you could modify it to get the file contents and do something with the file streams.

    var sb = new StringBuilder();
    
            var uh = new UmbracoHelper(UmbracoContext.Current);
            var homeNodes = uh.UmbracoContext.MediaCache.GetAtRoot();
    
            foreach (var homeNode in homeNodes)
            {
                sb.AppendLine(string.Format("{0},{1},TOP LEVEL FOLDER,n/a,{2}", homeNode.Id, homeNode.Name,
                    homeNode.GetPropertyValue<bool>("keep", false)));
                var mediaDescendants = homeNode.Descendants(20);
                foreach (var descendant in homeNode.Descendants())
                {
                    sb.AppendLine(string.Format("{0},{1},{2},{3},{4}", descendant.Id, homeNode.Name, descendant.AncestorOrSelf(1).Name,
                        descendant.DocumentTypeAlias.InvariantContains("folder") ? descendant.Name + "[Folder]" : descendant.Url, 
                        descendant.GetPropertyValue<bool>("keep", true, false)));
                }
            }
    
            var rootPath = HttpContext.Server.MapPath("~");
            var filePath = "media/AllMedia.csv";
            var fullPath = Path.Combine(rootPath, filePath);
    
            System.IO.File.WriteAllText(fullPath, sb.ToString());
    

    Hope that's of some use. Cheers, Andy

  • M N 125 posts 212 karma points
    Aug 09, 2018 @ 22:16
    M N
    3

    Searched around for something similar g3t .. Ended up having to write something,

    Below is a recursive function that should do what you want. It will make an exact copy of your Media Library structure, but in windows folder. Files are physically copied from the /media folder.

    private void ExportAllMedia(string basePath, string curFolder,  IMedia uNode)
    {
        var _contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
        var _mediaService = ApplicationContext.Current.Services.MediaService;
        var folderType = _contentTypeService.GetMediaType("Folder");
    
        Directory.CreateDirectory(curFolder);
    
        IEnumerable<IMedia> curMedia = null;
    
        if (uNode == null)
            curMedia = _mediaService.GetRootMedia();
        else
            curMedia = uNode.Children();
    
    
        // loop through folders
        foreach (IMedia media in curMedia.Where(a=>a.ContentTypeId == folderType.Id))
        {
            // recurse inward with this folder
            ExportAllMedia(basePath, curFolder + "\\"  + media.Name , media);
        }
    
        // regular files
        foreach (IMedia media in curMedia.Where(a => a.ContentTypeId != folderType.Id))
        {
            string filePath = media.GetValue<string>("umbracoFile").Replace("/", "\\");
            string source = basePath + filePath;
            string destination = Path.Combine(curFolder, Path.GetFileName(source));
    
            System.IO.File.Copy(source, destination);
        }
    }
    

    Usage

    string basepath = HttpContext.Current.Server.MapPath("~/").TrimEnd('\\');
    string savePath = HttpContext.Current.Server.MapPath("~/App_Data/ExportMedia/" + DateTime.Now.Ticks);
    ExportAllMedia(basepath, savePath, null);
    

    It won't zip it, but hey you can probably sort that out :)

    Cheers

  • Splinx 50 posts 186 karma points
    Dec 06, 2018 @ 17:32
    Splinx
    2

    Hi Guys,

    The post from M N was really helpful (thank you) but...

    ... it did not work for me as the umbracoFile types have JSON string return values if they are images but a simple path return value if they are any thing else (e.g. a pdf or video).

    I modified the above code a bit and now it's simple code that you can drop into a template and run it (no back end access required except for grabbing the generated files that is).

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    
    @{
        Layout = null;
    }
    
    @{
        debug = "";
    
        string basepath = HttpContext.Current.Server.MapPath("~/").TrimEnd('\\');
        string savePath = HttpContext.Current.Server.MapPath("~/App_Data/ExportMedia/" + DateTime.Now.Ticks);
    
        <div>basepath = @basepath</div>
        <div>savePath = @savePath</div>
        <br />
        <br />
    
        ExportAllMedia(basepath, savePath, null);
    
        @Html.Raw(debug);
    }
    
    @functions {
    
        // read-write variable for debug (I know it's nasty btw - quick and dirty view).
        public static string debug
        {
            get { return HttpContext.Current.Application["debug"] as string; }
            set { HttpContext.Current.Application["debug"] = value; }
        }
    
        private void ExportAllMedia(string basePath, string curFolder, IMedia uNode)
        {
    
            var _contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
            var _mediaService = ApplicationContext.Current.Services.MediaService;
            var folderType = _contentTypeService.GetMediaType("Folder");
    
            Directory.CreateDirectory(curFolder);
            IEnumerable<IMedia> curMedia = null;
    
            if (uNode == null)
            {
                curMedia = _mediaService.GetRootMedia();
            }
            else
            {
                curMedia = uNode.Children();
            }
    
            // loop through folders
            foreach (IMedia media in curMedia.Where(a => a.ContentTypeId == folderType.Id))
            {
                // recurse inward with this folder
                ExportAllMedia(basePath, curFolder + "\\" + media.Name, media);
    
            }
    
            // regular files
            foreach (IMedia media in curMedia.Where(a => a.ContentTypeId != folderType.Id))
            {
                string umbracoFile = media.GetValue<string>(Constants.Conventions.Media.File);
    
                string url = "";
                bool decoded = false;
    
                try
                {
                    var obj = Newtonsoft.Json.Linq.JObject.Parse(umbracoFile);
                    decoded = true;
                }
                catch (Exception ex)
                {
                    decoded = false;
                }
    
                if (decoded == true)
                {
                    url = Newtonsoft.Json.JsonConvert.DeserializeObject<Umbraco.Web.Models.ImageCropDataSet>(umbracoFile).Src;
                }
                else
                {
                    // No JSON so it must be a not cropped file type (e.g. PDF or similar)
                    url = umbracoFile;
                }
    
                string filePath = url.Replace("/", "\\");
                string source = basePath + filePath;
                string destination = Path.Combine(curFolder, Path.GetFileName(filePath));
    
                debug += "Exporting [" + source + "] to [" + destination + "]<br />";
    
                // IMPORTANT - Uncomment this to actually create the export !!!
                //System.IO.File.Copy(source, destination, true);
            }
        }
    }
    

    Cheers,

    Splinx :)

  • M N 125 posts 212 karma points
    Dec 06, 2018 @ 18:37
    M N
    1

    Wowzer. Might be because I changed my Image data type to use Image Cropper directly, so users didn't have to save images to their computer to upload them to an image cropper, they can just pick the image as one normally does in the Media Library, then crop it via Media Library.

    It works for anything, PDF, Video, JPG, etc. in that situation. Thanks for pointing it out!

    enter image description here

  • Splinx 50 posts 186 karma points
    Dec 06, 2018 @ 19:40
    Splinx
    0

    No worries buddy...

    It's all about community and your post really helped me out.

    I wanted to share my minor modifications so that it saved the next person a few minutes.

    Thanks again,

    Splinx.

  • g3t 32 posts 144 karma points
    Dec 12, 2018 @ 20:30
    g3t
    1

    Great work Splinx thanks so much for looking into this. And thanks everone for still looking into this post. It was a while back now but i still never got it sorted.... Until now :)

    Working really well

    I can just have \App_Data\ExportMedia Favorited now in browser and i can see whats being added to every folder now after running that page. plus getting back ups of everything. Spot on cheers.

  • Peter Kindberg 17 posts 107 karma points
    May 10, 2019 @ 11:40
    Peter Kindberg
    0

    Hi everyone,

    I'm running a project where we have both local dev server, stage server and prod server. I have created the following script that zip all files in your media and images folder, and allows you to download it locally. happy to share.

    I called this script "developerAid.aspx", with code-behind file developerAid.aspx.cs

    To make this work, you also need to add the page developerAid to the "umbracoReservedUrls" in web.config, so that Umbraco does not render the incoming request.

    ASPX-code:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="developerAid.aspx.cs" Inherits="developerAid_Default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div style="clear: both;">
                <select id="selectbox" runat="server">
                    <option>Zip Media Folder</option>
                    <option>Zip Images Folder</option>
                </select>
            </div>
        <div style="clear: both;">
            <input type="password" id="pass" runat="server"/>
        </div>
            <div style="clear: both;">
                <input type="submit" id="submit" runat="server"/>
            </div>
        </form>
        <label runat="server" id="status"></label>
    </body>
    </html>
    

    C# Code-behind file:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class developerAid_Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                submit_Click(sender, e);
    
            }
        }
    
        protected void submit_Click(object sender, EventArgs e)
        {
    
            if (!pass.Value.Equals("Some password here"))
            {
                status.InnerText = "Invalid password";
                return;
            }
            if (selectbox.Value.Equals("Zip Media Folder") || selectbox.Value.Equals("Zip Images Folder"))
            {
                string type = selectbox.Value.Equals("Zip Media Folder") ? "media" : "images";
                var bytes = ZipFolder(type);
                if (bytes != null)
                {
                    Response.Clear();
                    Response.BufferOutput = false;
                    var zipName = type+"_"+DateTime.Now.ToString("yyyy-MM-ddTHHmmss")+".zip";
                    Response.ContentType = "application/zip";
                    Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                    Response.BinaryWrite(bytes);
                    Response.End();
                }
            }
        }
    
        private byte[] ZipFolder(string folder)
        {
            var inputDirectory = MapPath("~/"+folder+"/");
            if (!Directory.Exists(inputDirectory))
            {
                status.InnerText = "Invalid path - codechange required";
                return null;
            }
            byte[] compressedBytes;
    
            using (var zipStream = new MemoryStream()) { 
                using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
                {
                    foreach (var filePath in Directory.GetFiles(inputDirectory, "*.*", SearchOption.AllDirectories))
                    {
                        var relativePath = filePath.Replace(inputDirectory, string.Empty);
                        if (relativePath.StartsWith("/"))
                            relativePath = relativePath.Substring(1);
                        using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                        using (var fileStreamInZip = archive.CreateEntry(relativePath).Open())
                            fileStream.CopyTo(fileStreamInZip);
                    }
                }
                compressedBytes = zipStream.ToArray();
            }
    
            return compressedBytes;
        }
    }
    

    I may appologize if the code is messy; it was developed for internal use only, and not for anyone else :)

    Hope it helps someone

    Best Regards

    Peter Kindberg

    Kindbergco.se/en

  • DonZalmrol 220 posts 833 karma points
    Nov 29, 2021 @ 14:14
    DonZalmrol
    0

    Pulling a very old cow from a ditch here, I've implemented the code from @Splinx and it works without any issues.

    My question is why is my exported media smaller then the original media folder?

    Its 109MB vs 800MB.: https://ibb.co/ws53fGw I reckon its partly due to caching being removed.

    PS: As a minor improvement I was able to program it in such a way that you can enable a bool from the backend and after it runs it disables it.

    My slightly edited version: https://pastebin.com/JETsJrqP

Please Sign in or register to post replies

Write your reply to:

Draft