Images in ASP.NET MVC Rich Text Editor Control

6 Mar 202524 minutes to read

Rich Text Editor allows to insert images in your content from online sources as well as local computer. For inserting an image to the Rich Text Editor, the following list of options have been provided in the InsertImageSettings

Configuring Image Tool in the Toolbar

You can add an Image tool in the Rich Text Editor toolbar using the ToolbarSettings Items property.

To configure the Image toolbar item, refer to the below code.

@Html.EJS().RichTextEditor("image").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertImageSettings(obj => obj.Display("inline")).Value(ViewBag.value).Render()
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.value = @"<p>The Syncfudion Rich Text Editor, a WYSIWYG (what you see is what you get) editor, is a user interface that allows you to create, edit, and format rich text content. You can try out a demo of this editor here.</p><p><b>Key features:</b></p><ul><li><p>Provides &lt;IFRAME&gt; and &lt;DIV&gt; modes.</p></li><li><p>Bulleted and numbered lists.</p></li><li><p>Handles images, hyperlinks, videos, hyperlinks, uploads, etc.</p></li><li><p>Contains undo/redo manager. </p></li></ul><div style='display: inline-block; width: 60%; vertical-align: top; cursor: auto;'><img alt='Sky with sun' src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Overview.png' width='309' style='min-width: 10px; min-height: 10px; width: 309px; height: 174px;' class='e-rte-image e-imginline e-rte-drag-image' height='174' /></div>";
        ViewBag.items = new[] { "Image" };
        return View();
    }
}

Supported Image Save Formats

The images can be saved as Blob or Base64 URL by using the InsertImageSettings.SaveFormat property, which is of enum type, and the generated URL will be set to the src attribute of the <source> tag.

<img src="blob:http://ej2.syncfusion.com/3ab56a6e-ec0d-490f-85a5-f0aeb0ad8879" >

<img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHA" >

The code snippet below illustrates the configuration of the InsertImageSettings.SaveFormat property in the Rich Text Editor.

The default SaveFormat property is set to Blob format.

Inserting Images from Web URLs

To insert an image from an online source, click the Image tool in the toolbar. By default, this tool opens a dialog box with an input field where you can provide the image URL from the web to insert the image.

Uploading Images from Local Machine

To insert an image from your local machine, click the Image tool in the toolbar. By default, this tool opens a dialog box where you can browse and select an image to insert from your local machine.

File Manager Integration for Image Insertion

To insert images from a file manager, enable the FileManager tool on the editor’s toolbar. This tool initiates a dialog where you can upload new images and choose from existing ones, facilitating smooth image insertion into your content.

To integrate the file manager into the Rich Text Editor, follow these steps:

  • Configure the FileManager toolbar item in the ToolbarSettings API Items property.
  • Set the Enable property to true in the FileManagerSettings property to ensure the file browser appears upon clicking the FileManager toolbar item.

Saving Image to Server

Upload the selected image to a specified destination using the controller action specified in InsertImageSettings.SaveUrl. Ensure to map this method name appropriately and provide the required destination path through the InsertImageSettings.Path properties.

Configure InsertImageSettings.RemoveUrl to point to the endpoint responsible for deleting image files.

Set the InsertImageSettings.SaveFormat property to determine whether the image should be saved as Blob or Base64, aligning with your application’s requirements.

NOTE

The runnable demo application is available in this Github repository.

@Html.EJS().RichTextEditor("defaultRTE").InsertImageSettings(obj => obj.SaveUrl("/Home/SaveImage").Path("../Uploads/")).Render()
using System;
using System.IO;
using ImageUpload.Models;
using System.Diagnostics;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;

namespace ImageUpload.Controllers
{
    public class HomeController : Controller
    {
        private IHostingEnvironment hostingEnv;

        public HomeController(IHostingEnvironment env)
        {
            hostingEnv = env;
        }

        public IActionResult Index()
        {
            return View();
        }

        [AcceptVerbs("Post")]
        public void SaveImage(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (IFormFile file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        filename = hostingEnv.WebRootPath + "\\Uploads" + $@"\{filename}";

                        // Create a new directory, if it does not exists
                        if (!Directory.Exists(hostingEnv.WebRootPath + "\\Uploads"))
                        {
                            Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Uploads");
                        }

                        if (!System.IO.File.Exists(filename))
                        {
                            using (FileStream fs = System.IO.File.Create(filename))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            Response.StatusCode = 200;
                        }
                    }
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 204;
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Image Renaming Feature

You can use the InsertImageSettings property, to specify the server handler to upload the selected image. Then by binding the FileUploadSuccess event, you can receive the modified file name from the server and update it in the Rich Text Editor’s insert image dialog.

Size-based Image Restrictions

You can restrict the image uploaded from the local machine when the uploaded image file size is greater than the allowed size by using the FileUploading event.

The file size in the argument will be returned in bytes.

Secure Image Upload with Authentication

You can add additional data with the image uploaded from the Rich Text Editor on the client side, which can even be received on the server side. By using the FileUploading event and its CustomFormData argument, you can pass parameters to the controller action. On the server side, you can fetch the custom headers by accessing the form collection from the current request, which retrieves the values sent using the POST method.

By default, it doesn’t support the UseDefaultCredentials property, you can manually append the default credentials with the upload request.

@Html.EJS().RichTextEditor("defaultRTE").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertImageSettings(obj => obj.SaveUrl("/Home/SaveFiles").FileUploading("onFileUploading").Path("../Files/")).Render()

<script>
    function onFileUploading(args) {
        var accessToken = "Authorization_token";
        // adding custom Form Data
        args.customFormData = [{ 'Authorization': accessToken }];
    }
</script>
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.items = new[] { "Audio" };
            return View();
        }

        [AcceptVerbs("Post")]
        public void SaveFiles(HttpPostedFileBase UploadFiles)
        {
            string currentPath = Request.Form["Authorization"].ToString();
            if (UploadFiles != null)
            {
                string path = Server.MapPath("~/Files/");

                // Create a new directory, if it does not exists
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                // Save a file in directory
                UploadFiles.SaveAs(path + Path.GetFileName(UploadFiles.FileName));
            }
        }
    }
}

Image Replacement Functionality

Once a image file has been inserted, you can replace it using the Rich Text Editor QuickToolbarSettings ImageReplace option. You can replace the image file either by using the web URL or the browse option in the image dialog.

Deleting Images

To remove an image from the Rich Text Editor content, select the image and click Remove tool from the quick toolbar. It will delete the image from the Rich Text Editor content as well as from the service location if the RemoveUrl is given.

Once you select the image from the local machine, the URL for the image will be generate. From there, you can remove the image from the service location by clicking the cross icon.

Rich Text Editor Image delete

The following sample explains, how to configure RemoveUrl to remove a saved image from the remote service location, when the following image remove actions are performed:

  • delete key action.
  • backspace key action.
  • Removing uploaded image file from the insert image dialog.
  • Deleting image using the quick toolbar Remove option.
@Html.EJS().RichTextEditor("RteImage").InsertImageSettings(obj => obj.SaveUrl("/Home/SaveImage").RemoveUrl("/Home/RemoveImage").Path("../Uploads/")).Render()
public class HomeController : Controller
{
    private IWebHostEnvironment hostingEnv;

    public HomeController(IWebHostEnvironment env)
    {
        hostingEnv = env;
    }

    public ActionResult Index()
    {
        return View();
    }

    [AcceptVerbs("Post")]
    public void SaveImage(IList<IFormFile> UploadFiles)
    {
        try
        {
            foreach (IFormFile file in UploadFiles)
            {
                if (UploadFiles != null)
                {
                    string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    filename = hostingEnv.WebRootPath + "\\Uploads" + $@"\{filename}";

                    // Create a new directory, if it does not exists
                    if (!Directory.Exists(hostingEnv.WebRootPath + "\\Uploads"))
                    {
                        Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Uploads");
                    }

                    if (!System.IO.File.Exists(filename))
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                        Response.StatusCode = 200;
                    }
                }
            }
        }
        catch (Exception)
        {
            Response.StatusCode = 204;
        }
    }

    [AcceptVerbs("Post")]
    public void RemoveImage(IList<IFormFile> UploadFiles)
    {
        try
        {
            foreach (IFormFile file in UploadFiles)
            {
                if (UploadFiles != null)
                {
                    // Do remove action here}
                    Response.StatusCode = 200;
                }
            }
        }
        catch (Exception)
        {
            Response.StatusCode = 204;
        }
    }
}

Adjusting Image Dimensions

Sets the default width and height of the image when it is inserted in the Rich Text Editor using Width and Height of the InsertImageSettings property.

Through the quick toolbar, change the width and height using Change Size option. Once you click, the Image Size dialog box will open as follows. In that you can specify the width and height of the image in pixel.

Rich Text Editor Image dimension

Adding Captions and Alt Text to Images

Image caption and alternative text can be specified for the inserted image in the Rich Text Editor through the QuickToolbarSettings property. It has following two options,

  • Image Caption
  • Alternative Text.

Through the Alternative Text option, set the alternative text for the image, when the image is not upload successfully into the Rich Text Editor.

By clicking the Image Caption, the image will get wrapped in an image element with a caption. Then, you can type caption content inside the Rich Text Editor.

Configuring Image Display Position

Sets the default display for an image when it is inserted in the Rich Text Editor using Display field in InsertImageSettings. It has two possible options: ‘inline’ and ‘block’.

@Html.EJS().RichTextEditor("image").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertImageSettings(obj => obj.Display("break")).Value(ViewBag.value).Render()
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.value = @"<p>The Syncfudion Rich Text Editor, a WYSIWYG (what you see is what you get) editor, is a user interface that allows you to create, edit, and format rich text content. You can try out a demo of this editor here.</p><p><b>Key features:</b></p><ul><li><p>Provides &lt;IFRAME&gt; and &lt;DIV&gt; modes.</p></li><li><p>Bulleted and numbered lists.</p></li><li><p>Handles images, hyperlinks, videos, hyperlinks, uploads, etc.</p></li><li><p>Contains undo/redo manager. </p></li></ul><div style='display: inline-block; width: 60%; vertical-align: top; cursor: auto;'><img alt='Sky with sun' src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Overview.png' width='309' style='min-width: 10px; min-height: 10px; width: 309px; height: 174px;' class='e-rte-image e-imginline e-rte-drag-image' height='174' /></div>";
        ViewBag.items = new[] { "Image" };
        return View();
    }
}

Hyperlinking Images

The hyperlink itself can be an image in Rich Text Editor. If the image given as hyperlink, remove, edit and open link will be added to the quick toolbar of image. For further details about link, see the link documentation documentation.

Rich Text Editor image with link

Image Resizing Tools

Rich Text Editor has a built-in image inserting support. The resize points will be appearing on each corner of image when focus. So, users can resize the image using mouse points or thumb through the resize points easily. Also, the resize calculation will be done based on aspect ratio.

Rich Text Editor image resize

Configuring Allowed Image Types

You can allow the specific images alone to be uploaded using the the allowedTypes property. By default, the Rich Text Editor allows the JPG, JPEG, and PNG formats. You can configure this formats as follows.

    InsertImageSettings(e=>e.AllowedTypes(new []{".jpg"}))

Drag and Drop Image Insertion

By default, the Rich Text Editor allows you to insert images by drag-and-drop from the local file system such as Windows Explorer into the content editor area. And, you can upload the images to the server before inserting into the editor by configuring the saveUrl property. The images can be repositioned anywhere within the editor area by dragging and dropping the image.

In the following sample, you can see feature demo.

@Html.EJS().RichTextEditor("drag-drop").InsertImageSettings(obj => obj.SaveUrl("https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save")).Value(ViewBag.value).Render()
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.value = @"<p>The Syncfudion Rich Text Editor, a WYSIWYG (what you see is what you get) editor, is a user interface that allows you to create, edit, and format rich text content. You can try out a demo of this editor here.</p><p><b>Key features:</b></p><ul><li><p>Provides &lt;IFRAME&gt; and &lt;DIV&gt; modes.</p></li><li><p>Bulleted and numbered lists.</p></li><li><p>Handles images, hyperlinks, videos, hyperlinks, uploads, etc.</p></li><li><p>Contains undo/redo manager. </p></li></ul><div style='display: inline-block; width: 60%; vertical-align: top; cursor: auto;'><img alt='Sky with sun' src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Overview.png' width='309' style='min-width: 10px; min-height: 10px; width: 309px; height: 174px;' class='e-rte-image e-imginline e-rte-drag-image' height='174' /></div>";
        return View();
    }
}

Disabling Drag and Drop for Images

You can prevent drag-and-drop action by setting the actionBegin argument cancel value to true. The following code shows how to prevent the drag-and-drop.

Customizing the Image Quick Toolbar

The Rich Text Editor allows you to customize the image quick toolbar, providing essential tools such as ‘Replace’, ‘Align’, ‘Caption’, ‘Remove’, ‘InsertLink’, ‘Display’, ‘AltText’, and ‘Dimension’.

By configuring these options in the QuickToolbarSettings property, you can enhance the editor’s functionality, enabling seamless image management and editing directly within your content. This customization ensures a user-friendly experience for efficiently manipulating image elements.

@Html.EJS().RichTextEditor("image-quick-toolbar").ToolbarSettings(e => e.Items((object)ViewBag.items)).QuickToolbarSettings(e => { e.Image((object)ViewBag.image); }).Value(ViewBag.value).Render()
public class HomeController : Controller
{

    public ActionResult Index()
    {
        ViewBag.value = @"<p>The Syncfudion Rich Text Editor, a WYSIWYG (what you see is what you get) editor, is a user interface that allows you to create, edit, and format rich text content. You can try out a demo of this editor here.</p><p><b>Key features:</b></p><ul><li><p>Provides &lt;IFRAME&gt; and &lt;DIV&gt; modes.</p></li><li><p>Bulleted and numbered lists.</p></li><li><p>Handles images, hyperlinks, videos, hyperlinks, uploads, etc.</p></li><li><p>Contains undo/redo manager. </p></li></ul><div style='display: inline-block; width: 60%; vertical-align: top; cursor: auto;'><img alt='Sky with sun' src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Overview.png' width='309' style='min-width: 10px; min-height: 10px; width: 309px; height: 174px;' class='e-rte-image e-imginline e-rte-drag-image' height='174' /></div>";
        ViewBag.items = new[] { "Image" };
        ViewBag.image = new[] { "Replace", "Align", "Caption", "Remove", "InsertLink", "OpenImageLink", "-",
            "EditImageLink", "RemoveImageLink", "Display", "AltText", "Dimension" };
        return View();
    }
}

See Also