Umbraco v6: Export des médias dans un ZIP
Description
Ce contrôleur exporte tous les médias d'un site Umbraco version 6 vers un dossier local. Il parcourt récursivement l'arborescence des médias et copie les fichiers tout en conservant la structure des dossiers.
Code
csharp
using System;
using System.IO;
using System.Web.Hosting;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.WebApi;
namespace Nanoxi.App.Api.Controllers
{
/// <summary>
/// Summary description for MediaExportController
/// </summary>
public class MediaExportController : UmbracoApiController
{
private string targetFolder = "~/App_Data/mediaExport";
public string GetPath()
{
var fullExportPath = HostingEnvironment.MapPath(targetFolder);
if (fullExportPath == null)
{
throw new DirectoryNotFoundException(targetFolder);
}
if (Directory.Exists(fullExportPath))
{
// delete the current export
Directory.Delete(fullExportPath, true);
}
var exportDirectory = new DirectoryInfo(fullExportPath);
var rootMedias = Umbraco.TypedMediaAtRoot();
foreach (var rootMedia in rootMedias)
{
TraverseFolder(rootMedia, exportDirectory);
}
return targetFolder;
}
private void TraverseFolder(IPublishedContent rootMedia, DirectoryInfo directory)
{
// If current item is not a folder
if (rootMedia.ItemType == PublishedItemType.Media && rootMedia.DocumentTypeAlias != "Folder")
{
// store rootMedia.Path
var fileValue = rootMedia.GetPropertyValue<string>(Constants.Conventions.Media.File);
if (string.IsNullOrWhiteSpace(fileValue))
{
LogHelper.Warn<MediaExportController>($"Media without file skipped: {rootMedia.Id} ({rootMedia.Name})");
return;
}
var srcPath = HostingEnvironment.MapPath(fileValue);
var fileInfo = new FileInfo(srcPath);
try
{
System.IO.File.Copy(srcPath, directory.FullName + "\\" + fileInfo.Name);
}
catch (Exception ex)
{
//if (Debugger.IsAttached) Debugger.Break();
LogHelper.Error<MediaExportController>("could not copy", ex);
}
return;
}
// If current item is a folder,
// Create subfolder
var folderName = rootMedia.UrlName;
var newFolder = directory.CreateSubdirectory(folderName);
// and loop children
foreach (var mediaItem in rootMedia.Children)
{
TraverseFolder(mediaItem, newFolder);
}
}
}
}Comment ça marche
Le contrôleur expose une méthode GetPath() qui:
- Supprime l'exportation existante dans
~/App_Data/mediaExport - Parcourt tous les éléments multimédias racine
- Copie les fichiers tout en recréant la structure des dossiers (dont enfants..)
- Renvoie le chemin d'accès au dossier d'exportation

