For a similar requirement, I have used both Sitecore Powershell and C#.
Here is the code in C#
namespace Sitecore.Extension.ImageUpload
{
using System.Collections.Generic;
using System.IO;
using System.Text;
using Sitecore.Configuration;
using Sitecore.Data.Items;
using Sitecore.Resources.Media;
public static class MediaUploader
{
public static string TriggerUpload(string directory, string sitecorePath)
{
var sb = new StringBuilder();
var filesWithPath = DirSearch(directory);
foreach (var filePath in filesWithPath.Keys)
{
sb.AppendLine($"Processing {filePath}");
var myFile = AddFile(filePath, sitecorePath, filesWithPath[filePath]);
sb.AppendLine(myFile != null
? $"[SUCCES] File {myFile.Name} added successfully"
: $"[FAIL] Fail to add file with path {filePath}");
}
return sb.ToString();
}
public static MediaItem AddFile(string fileName, string sitecorePath, string path)
{
path = path.Replace("\\\\", "\\");
// Create the options
MediaCreatorOptions options = new MediaCreatorOptions
{
FileBased = false,
IncludeExtensionInItemName = false,
OverwriteExisting = false,
Versioned = false,
Destination = sitecorePath + "/" + fileName.Replace(".jpg", string.Empty).Replace(".png", string.Empty).Replace(".jpeg", string.Empty),
Database = Factory.GetDatabase("master")
};
// Now create the file
var creator = new MediaCreator();
var mediaItem = creator.CreateFromFile(path, options);
return mediaItem;
}
private static Dictionary<string, string> DirSearch(string sDir)
{
var files = new Dictionary<string, string>();
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(Path.GetFileName(f), f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
DirSearch(d);
}
return files;
}
}
}
And the Powershell Script is
$paths = @(
"$AppPath/images/mysite/banners=/sitecore/media library/my site/banners",
"$AppPath/images/mysite/main banners=/sitecore/media library/my site/main banners"
)
foreach($path in $paths){
$splitter = $path -split "="
"Executing for $splitter[0]"
New-UsingBlock (New-Object Sitecore.SecurityModel.SecurityDisabler) {
New-UsingBlock (New-Object Sitecore.Data.DatabaseCacheDisabler) {
New-UsingBlock (New-Object Sitecore.Data.Events.EventDisabler) {
New-UsingBlock (New-Object Sitecore.Data.BulkUpdateContext) {
$results = [Sitecore.Extension.ImageUpload.MediaUploader]::TriggerUpload($splitter[0], $splitter[1])
$results
}
}
}
}
"-----------------------------------------------"
}
In the script, you need to set the path of the image directory where it resides on the server and the destination path.
'image path on server'='destination of images in Sitecore'
Once completed, you need to clear the Sitecore Cache via the cache.aspx
page