By default, the Insert Image tool opens a simple dialog that allows you to type in or paste the URL of an image and, optionally, specify a tooltip.
The Editor also supports another way of picking an image by browsing a list of predefined files and directories. Uploading new images is also supported. For a runnable example, refer to the demo on file and image browser in the Editor.
To retrieve and upload the files and directories, the image browser needs a server-side implementation. To configure the image browser tool, use the ImageBrowser() method.
publicclassImageBrowserController:EditorImageBrowserController{privateconststring contentFolderRoot ="shared/";privateconststring folderName ="Images/";privatestaticreadonlystring[] foldersToCopy =new[]{"shared/images/employees"};/// <summary>/// Gets the base paths from which content will be served./// </summary>publicoverridestring ContentPath
{get{returnCreateUserFolder();}}publicImageBrowserController(IHostingEnvironment hostingEnvironment):base(hostingEnvironment){}privatestringCreateUserFolder(){var virtualPath = Path.Combine(contentFolderRoot,"UserFiles", folderName);var path = HostingEnvironment.WebRootFileProvider.GetFileInfo(virtualPath).PhysicalPath;if(!Directory.Exists(path)){
Directory.CreateDirectory(path);foreach(var sourceFolder in foldersToCopy){CopyFolder(HostingEnvironment.WebRootFileProvider.GetFileInfo(sourceFolder).PhysicalPath, path);}}return virtualPath;}privatevoidCopyFolder(string source,string destination){if(!Directory.Exists(destination)){
Directory.CreateDirectory(destination);}foreach(var file in Directory.EnumerateFiles(source)){var dest = Path.Combine(destination, Path.GetFileName(file));
System.IO.File.Copy(file, dest);}foreach(var folder in Directory.EnumerateDirectories(source)){var dest = Path.Combine(destination, Path.GetFileName(folder));CopyFolder(folder, dest);}}}
C#
publicabstractclassEditorImageBrowserController:BaseFileBrowserController,IImageBrowserController{protectedEditorImageBrowserController(IHostingEnvironment hostingEnvironment):this(DI.Current.Resolve<IDirectoryBrowser>(),
DI.Current.Resolve<IDirectoryPermission>(),
hostingEnvironment){}protectedEditorImageBrowserController(IDirectoryBrowser directoryBrowser,IDirectoryPermission permission,IHostingEnvironment hostingEnvironment):base(directoryBrowser, permission, hostingEnvironment){}/// <summary>/// Gets the valid file extensions by which served files will be filtered./// </summary>publicoverridestring Filter
{get{return EditorImageBrowserSettings.DefaultFileTypes;}}publicvirtualboolAuthorizeThumbnail(string path){returnCanAccess(path);}/// <summary>/// You can use a third-party library to create thumbnails as System.Drawing is not curretnly part of ASP.NET Core https://blogs.msdn.microsoft.com/dotnet/2016/02/10/porting-to-net-core//// </summary>publicvirtualIActionResultThumbnail(string path){returnnull;}}
C#
publicabstractclassBaseFileBrowserController:Controller,IFileBrowserController{privatereadonlyIDirectoryBrowser directoryBrowser;privatereadonlyIDirectoryPermission permission;protectedreadonlyIHostingEnvironment HostingEnvironment;protectedBaseFileBrowserController(IHostingEnvironment hostingEnvironment):this(DI.Current.Resolve<IDirectoryBrowser>(),
DI.Current.Resolve<IDirectoryPermission>(),
hostingEnvironment){}protectedBaseFileBrowserController(IDirectoryBrowser directoryBrowser,IDirectoryPermission permission,IHostingEnvironment hostingEnvironment){this.directoryBrowser = directoryBrowser;this.directoryBrowser.HostingEnvironment = hostingEnvironment;this.permission = permission;this.HostingEnvironment = hostingEnvironment;}/// <summary>/// Gets the base path from which content will be served./// </summary>publicabstractstring ContentPath
{get;}/// <summary>/// Gets the valid file extensions by which served files will be filtered./// </summary>publicvirtualstring Filter
{get{return"*.*";}}/// <summary>/// Creates a folder with a given entry./// </summary>/// <paramname="path">The path to the parent folder in which the folder should be created.</param>/// <paramname="entry">The entry.</param>/// <returns>An empty <seecref="ContentResult"/>.</returns>/// <exceptioncref="Exception">Forbidden</exception>[AcceptVerbs("POST")]publicvirtualActionResultCreate(string path,FileBrowserEntry entry){var fullPath =NormalizePath(path);var name = entry.Name;if(name.HasValue()&&AuthorizeCreateDirectory(fullPath, name)){var physicalPath = Path.Combine(fullPath, name);if(!Directory.Exists(physicalPath)){
Directory.CreateDirectory(physicalPath);}returnJson(entry);}thrownewException("Forbidden");}/// <summary>/// Determines if a folder can be created./// </summary>/// <paramname="path">The path to the parent folder in which the folder should be created.</param>/// <paramname="name">Name of the folder.</param>/// <returns>true if folder can be created, otherwise false.</returns>publicvirtualboolAuthorizeCreateDirectory(string path,string name){returnCanAccess(path);}publicvirtualJsonResultRead(string path){var fullPath =NormalizePath(path);if(AuthorizeRead(fullPath)){try{var files = directoryBrowser.GetFiles(fullPath, Filter);var directories = directoryBrowser.GetDirectories(fullPath);var result = files.Concat(directories);returnJson(result.ToArray());}catch(DirectoryNotFoundException){thrownewException("File Not Found");}}thrownewException("Forbidden");}/// <summary>/// Determines if content of a given path can be browsed./// </summary>/// <paramname="path">The path which will be browsed.</param>/// <returns>true if browsing is allowed, otherwise false.</returns>publicvirtualboolAuthorizeRead(string path){returnCanAccess(path);}protectedvirtualboolCanAccess(string path){var rootPath = Path.GetFullPath(Path.Combine(this.HostingEnvironment.WebRootPath, ContentPath));return permission.CanAccess(rootPath, path);}protectedstringNormalizePath(string path){if(string.IsNullOrEmpty(path)){return Path.GetFullPath(Path.Combine(this.HostingEnvironment.WebRootPath, ContentPath));}else{return Path.GetFullPath(Path.Combine(this.HostingEnvironment.WebRootPath, ContentPath, path));}}/// <summary>/// Deletes a entry./// </summary>/// <paramname="path">The path to the entry.</param>/// <paramname="entry">The entry.</param>/// <returns>An empty <seecref="ContentResult"/>.</returns>/// <exceptioncref="Exception">File Not Found</exception>[AcceptVerbs("POST")]publicvirtualActionResultDestroy(string path,FileBrowserEntry entry){var fullPath =NormalizePath(path);if(entry !=null){
fullPath = Path.Combine(fullPath, entry.Name);if(entry.EntryType == FileBrowserEntryType.File){DeleteFile(fullPath);}else{DeleteDirectory(fullPath);}returnJson(newobject[0]);}thrownewException("File Not Found");}/// <summary>/// Determines if a file can be deleted./// </summary>/// <paramname="path">The path to the file.</param>/// <returns>true if file can be deleted, otherwise false.</returns>publicvirtualboolAuthorizeDeleteFile(string path){returnCanAccess(path);}/// <summary>/// Determines if a folder can be deleted./// </summary>/// <paramname="path">The path to the folder.</param>/// <returns>true if folder can be deleted, otherwise false.</returns>publicvirtualboolAuthorizeDeleteDirectory(string path){returnCanAccess(path);}protectedvirtualvoidDeleteFile(string path){if(!AuthorizeDeleteFile(path)){thrownewException("Forbidden");}if(System.IO.File.Exists(path)){
System.IO.File.Delete(path);}}protectedvirtualvoidDeleteDirectory(string path){if(!AuthorizeDeleteDirectory(path)){thrownewException("Forbidden");}if(Directory.Exists(path)){
Directory.Delete(path,true);}}/// <summary>/// Uploads a file to a given path./// </summary>/// <paramname="path">The path to which the file should be uploaded.</param>/// <paramname="file">The file which should be uploaded.</param>/// <returns>A <seecref="JsonResult"/> containing the uploaded file's size and name.</returns>/// <exceptioncref="Exception">Forbidden</exception>[AcceptVerbs("POST")]publicvirtualActionResultUpload(string path,IFormFile file){var fullPath =NormalizePath(path);if(AuthorizeUpload(fullPath, file)){SaveFile(file, fullPath);var result =newFileBrowserEntry{
Size = file.Length,
Name =GetFileName(file)};returnJson(result);}thrownewException("Forbidden");}protectedvirtualvoidSaveFile(IFormFile file,string pathToSave){try{var path = Path.Combine(pathToSave,GetFileName(file));using(var stream = System.IO.File.Create(path)){
file.CopyTo(stream);}}catch(Exception ex){thrownewException(ex.Message);}}/// <summary>/// Determines if a file can be uploaded to a given path./// </summary>/// <paramname="path">The path to which the file should be uploaded.</param>/// <paramname="file">The file which should be uploaded.</param>/// <returns>true if the upload is allowed, otherwise false.</returns>publicvirtualboolAuthorizeUpload(string path,IFormFile file){returnCanAccess(path)&&IsValidFile(GetFileName(file));}privateboolIsValidFile(string fileName){var extension = Path.GetExtension(fileName);var allowedExtensions = Filter.Split(',');return allowedExtensions.Any(e => e.Equals("*.*")|| e.EndsWith(extension, StringComparison.OrdinalIgnoreCase));}publicvirtualstringGetFileName(IFormFile file){var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);return Path.GetFileName(fileContent.FileName.ToString().Trim('"'));}}
Read()—Makes a POST request that contains the path parameter which specifies the path that is browsed and expects a file listing in the following format.
name from the previous example is the name of the file or directory, type is either an f for a file or a d for a directory, and size is the file size (optional).
Destroy()—Makes a POST request with the following parameters and expects an empty ContentResult as a response:
Parameter
Description
name
The file or the directory that will be deleted.
path
The directory in which the file or the directory resides.
type
The file or the directory that will be deleted (an f or a d).
size
(Optional) The file size, as provided by the Read() response.
Upload()—Makes a POST request. The request includes FormData which contains the upload path and the file name and type. Its payload consists of the uploaded file. The expected response is a file object in the following format:
JS
{"name":"foo.png","type":"f","size":12345}
Image()—Used by the Editor to generate the src attribute of the original image when the image is inserted. It results in a GET request generated by the browser for each inserted image. The URL can point to a file system or to a service and is parameterized—the {0} placeholder denotes the path and fileName as received from the Read() service.
You can update all of these requests and responses through the ImageBrowser() configuration. Each of them exposes more options that you can tweak.
In order to set up the ImageBrowser of the Telerik UI Editor for ASP.NET Core component in Razor page scenario, you need to configure the Read , Create, Update and Destroy methods of the ImageBrowser Transport configuration. The URL in these methods should refer the name of the handler in the PageModel. See the implementation details in the example below, and for the full project with RazorPages examples, visit our GitHub repository.