Videos in EJ2 TypeScript Rich text editor control

22 Mar 202524 minutes to read

The Rich Text Editor allows you to insert videos from online sources and local computers into your content. You can insert the video with the following list of options in the insertVideoSettings property.

Configuring the Video Tool in the Toolbar

You can add the Video tool in the Rich Text Editor toolbar using the toolbarSettings items property.

Rich Text Editor features are segregated into individual feature-wise modules. To use video tool, inject video module using the RichTextEditor.Inject(Video).

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

import { RichTextEditor, HtmlEditor, Toolbar, QuickToolbar, Video } from '@syncfusion/ej2-richtexteditor';
RichTextEditor.Inject(HtmlEditor, Toolbar, QuickToolbar, Video);

let defaultRTE: RichTextEditor = new RichTextEditor({
    value: `<p>Rich Text Editor allows inserting video and audio from online sources and the local computers where you want to insert a video and audio into your content.</p>`,
    toolbarSettings: {
        items: ['Video']
    }
});
defaultRTE.appendTo('#defaultRTE');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 Rich Text Editor</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-lists/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-navigations/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-richtexteditor/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='defaultRTE'> 
        </div>
    </div>
</body>

</html>

Video Save Formats

The video files can be saved as Blob or Base64 URLs by using the insertVideoSettings.saveFormat property, which is of enum type, and the generated URL will be set to the src attribute of the <source> tag.

The default saveFormat property is set to Blob format.

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

<video>
    <source src="data:video/mp4;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHA" type="video/mp4" >
</video>

Inserting Video from Web

You can insert a video from either a hosted link or your local machine by clicking the video button in the editor’s toolbar. When you click the video button, a dialog opens, allowing you to insert a video using an Embedded code or Web URL.

Inserting Video via Embed URL

The insert video dialog opens with the Embedded code option selected by default. This allows you to insert a video using embedded code.

Javascript Rich Text Editor Embed URL Video insert

Inserting Video via Web URL

You can switch to the Web URL option by selecting the Web URL checkbox. Inserting a video using the Web URL option will add the video URL as the src attribute of the <source> tag.

Javascript Rich Text Editor Video insert

Uploading Video from Local Machine

You can use the browse option on the video dialog to select the video from the local machine and insert it into the Rich Text Editor content.

If the path field is not specified in the insertVideoSettings, the video will be converted into the Blob URL or Base64 and inserted inside the Rich Text Editor.

Saving Video to the Server

Upload the selected video to a specified destination using the controller action specified in insertVideoSettings.saveUrl. Ensure to map this method name appropriately and provide the required destination path through the insertVideoSettings.path properties.

Configure insertVideoSettings.removeUrl to point to the endpoint responsible for deleting video files.

Set the insertVideoSettings.saveFormat property to determine whether the video should be saved as Blob or Base64, aligning with your application’s requirements.

If you want to insert lower-sized video files in the editor and don’t require a specific physical location for saving the video, you can save the format as Base64.

In the following code blocks, the video module has been injected and can insert the video files saved in the specified path.

import { RichTextEditor, Toolbar, Video, Link, HtmlEditor, QuickToolbar } from '@syncfusion/ej2-richtexteditor';
RichTextEditor.Inject(Toolbar, Video, Link, HtmlEditor, QuickToolbar );

let defaultRTE: RichTextEditor = new RichTextEditor({
    toolbarSettings: {
        items: ['Video']
    },
    insertVideoSettings: {
        saveUrl: "[SERVICE_HOSTED_PATH]/api/uploadbox/SaveFiles",
        path: "[SERVICE_HOSTED_PATH]/Files/"
    }
});
defaultRTE.appendTo('#defaultRTE');
using System;
using System.IO;
using FileUpload.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 FileUpload.Controllers
{
    public class HomeController : Controller
    {
        private IHostingEnvironment hostingEnv;

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

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

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

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

                        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 });
        }
    }
}

Renaming Video Before Inserting

You can use the insertVideoSettings property to specify the server handler to upload the selected video. 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 video dialog.

<div id='defaultRTE'></div>
import { RichTextEditor, Toolbar, Link, Video, Count, HtmlEditor, QuickToolbar } from '@syncfusion/ej2-richtexteditor';
RichTextEditor.Inject(Toolbar, Link, Video, Count, HtmlEditor, QuickToolbar);

let defaultRTE: RichTextEditor = new RichTextEditor({
        toolbarSettings: {
            items: ['Video']
        },
        value: ` <p>The Rich Text Editor is WYSIWYG ("what you see is what you get") editor useful to create and edit content, and return the valid <a href="https://ej2.syncfusion.com/home/" target="_blank">HTML markup</a> or <a href="https://ej2.syncfusion.com/home/" target="_blank">markdown</a> of the content</p>`,
        insertVideoSettings: {
            saveUrl: "[SERVICE_HOSTED_PATH]/api/uploadbox/Rename",
            path: "[SERVICE_HOSTED_PATH]/Files/"
        },
        fileUploadSuccess: onFileUploadSuccess
    });
defaultRTE.appendTo('#defaultRTE');

function onFileUploadSuccess (args: any) {
    alert("Get the new file name here");
    if (args.e.currentTarget.getResponseHeader('name') != null) {
        args.file.name = args.e.currentTarget.getResponseHeader('name');
        let filename: any = document.querySelectorAll(".e-file-name")[0];
        filename.innerHTML = args.file.name.replace(document.querySelectorAll(".e-file-type")[0].innerHTML, '');
        filename.title = args.file.name;
    }
}

To configure server-side handler, refer to the below code.

int x = 0;
string file;
[AcceptVerbs("Post")]
public void Rename()
{
    try
    {
        var httpPostedFile = System.Web.HttpContext.Current.Request.Files["UploadFiles"];
        fileName = httpPostedFile.FileName;
        if (httpPostedFile != null)
        {
            var fileSave = System.Web.HttpContext.Current.Server.MapPath("~/Files");
            if (!Directory.Exists(fileSave))
            {
                Directory.CreateDirectory(fileSave);
            }
            var fileName = Path.GetFileName(httpPostedFile.FileName);
            var fileSavePath = Path.Combine(fileSave, fileName);
            while (System.IO.File.Exists(fileSavePath))
            {
                fileName = "rteFiles" + x + "-" + fileName;
                fileSavePath = Path.Combine(fileSave, fileName);
                x++;
            }
            if (!System.IO.File.Exists(fileSavePath))
            {
                httpPostedFile.SaveAs(fileSavePath);
                HttpResponse Response = System.Web.HttpContext.Current.Response;
                Response.Clear();
                Response.Headers.Add("name", fileName);
                Response.ContentType = "application/json; charset=utf-8";
                Response.StatusDescription = "File uploaded succesfully";
                Response.End();
            }
        }
    }
    catch (Exception e)
    {
        HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.StatusCode = 204;
        Response.Status = "204 No Content";
        Response.StatusDescription = e.Message;
        Response.End();
    }
}

Restricting Video by Size

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

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

In the following example, the video size has been validated before uploading and determined whether the video has been uploaded or not.

import { RichTextEditor, Toolbar, Link, Video, Count, HtmlEditor, QuickToolbar } from '@syncfusion/ej2-richtexteditor';
import { UploadingEventArgs } from '@syncfusion/ej2-inputs';
RichTextEditor.Inject(Toolbar, Link, Video, Count, HtmlEditor, QuickToolbar);

let defaultRTE: RichTextEditor = new RichTextEditor({
        toolbarSettings: {
            items: ['Video']
        },
        insertVideoSettings: {
            saveUrl: "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save",
            path: "../Files/"
        },
        fileUploading: onFileUpload
    });
defaultRTE.appendTo('#defaultRTE');

function onFileUpload (args: UploadingEventArgs): void {
    let sizeInBytes: number = args.fileData.size;
    let fileSize: number = 500000;
    if (fileSize < sizeInBytes) {
        args.Cancel = true;
    }
}

Uploading Video with Authentication

You can add additional data with the video 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.

import { RichTextEditor, Toolbar, Link, Video, Count, HtmlEditor, QuickToolbar } from '@syncfusion/ej2-richtexteditor';
RichTextEditor.Inject(Toolbar, Link, Video, Count, HtmlEditor, QuickToolbar);

let defaultRTE: RichTextEditor = new RichTextEditor({
        toolbarSettings: {
            items: ['Video']
        },
        insertVideoSettings: {
            saveUrl: "[SERVICE_HOSTED_PATH]/api/uploadbox/SaveFiles",
            path: "[SERVICE_HOSTED_PATH]/Files/"
        },
        fileUploading: onFileUpload
    });
defaultRTE.appendTo('#defaultRTE');

function onFileUpload (args: UploadingEventArgs): void {
    var accessToken = "Authorization_token";
    // adding custom Form Data
    args.customFormData = [{ 'Authorization': accessToken }];
}
public void SaveFiles(IList<IFormFile> UploadFiles)
{
    string currentPath = Request.Form["Authorization"].ToString();
}

Video Replacement Functionality

Once a video file has been inserted, you can replace it using the Rich Text Editor quickToolbarSettings videoReplace option. You can replace the video file either by using the embedded code or the web URL and the browse option in the video dialog.

Javascript Rich Text Editor Embed Video Replace

Javascript Rich Text Editor Web Video Replace

Deleting Video

To remove a video from the Rich Text Editor content, select the video and click the videoRemove button from the quick toolbar. It will delete the video from the Rich Text Editor content as well as from the service location if the insertVideoSettings.removeUrl is given.

Once you select the video from the local machine, the URL for the video will be generated. You can remove the video from the service location by clicking the cross icon.

Javascript Rich Text Editor Video delete

Adjusting Video Dimensions

Set the default width, minWidth, height, and minHeight of the video element when it is inserted in the Rich Text Editor using the width, minWidth, height, minHeight properties.

Through the quickToolbarSettings, you can also change the width and height using the Change Size button. Once you click on the button, the video size dialog will open as below. In that, specify the width and height of the video in pixels.

Javascript Rich Text Editor Video dimension

Configuring Video Display Position

Sets the default display property for the video when it is inserted in the Rich Text Editor using the insertVideoSettings.layoutOption property. It has two possible options: Inline and Break. When updating the display positions, it updates the video elements’ layout position.

The default layoutOption property is set to Inline.

let defaultRTE: RichTextEditor = new RichTextEditor({
    insertVideoSettings: {
        layoutOption: 'Inline'
    }
});
defaultRTE.appendTo('#defaultRTE');

Video Resizing Tools

The Rich Text Editor has built-in video resizing support, which is enabled for the video elements added. The resize points will appear on each corner of the video when focusing, so users can easily resize the video using mouse points or thumb through the resize points. Also, the resize calculation will be done based on the aspect ratio.

You can disable the resize action by configuring false for the insertVideoSettings.resize property.

If the minWidth and minHeight properties are configured, the video resizing does not shrink below the specified values.

Javascript Rich Text Editor video resize

Customizing the Video Quick Toolbar

The Rich Text Editor enables customization of the video quick toolbar, allowing you to tailor its functionality with essential tools such as VideoReplace, VideoAlign, VideoRemove, VideoLayoutOption, and VideoDimension.

By configuring these options in the quickToolbarSettings property, you enhance the editor’s capabilities, facilitating seamless management and editing of embedded videos directly within your content. This customization ensures a user-friendly experience for manipulating video elements efficiently.

import { RichTextEditor, Toolbar, Link, Video, Image, HtmlEditor, QuickToolbar} from '@syncfusion/ej2-richtexteditor';
RichTextEditor.Inject(Toolbar, Link, Image, Video, HtmlEditor, QuickToolbar);
 
// Initialize Rich Text Editor component
let editor: RichTextEditor = new RichTextEditor({
  toolbarSettings: {
    items: ['Video']
  },
  quickToolbarSettings: {
    showOnRightClick: true,
    video: ['VideoReplace', 'VideoAlign', 'VideoRemove', 'VideoLayoutOption', 'VideoDimension']
  },
  value: `<p><b>Get started with Quick Toolbar to click on a video</b></p>
            <p>Using the quick toolbar, users can replace, align, display, dimension, and delete the selected video.</p>
            <p><video controls style="width: 30%;">
                <source
                  src="https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Ocean-Waves.mp4"
                  type="video/mp4" />
              </video></p> `
});
 
editor.appendTo('#defaultRTE');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 Rich Text Editor</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-lists/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-navigations/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/29.1.33/ej2-richtexteditor/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='defaultRTE'></div>
    </div>
</body>

</html>

See Also