Insert Video in Blazor RichTextEditor Component

18 Aug 202324 minutes to read

Once a video file has been inserted, replace it using the Rich Text Editor RichTextEditorQuickToolbarSettings Replace option. Replace the video file either by using the embedded URL or the web URL and the browse option in the video dialog.

Options Description
AllowedTypes Specifies the extensions of the video types allowed to insert on bowering and passing the extensions with comma separators. For example, pass allowedTypes as .mp4, .mov, .wmv, and .avi.
VideoLayoutOption Sets the default display for a video when it is inserted into the Rich Text Editor. Possible options are Inline and Break.
SaveFormat Sets the default save format of the video element when inserted. Possible options are Blob and Base64.
Width Sets the default width of the video when it is inserted in the Rich Text Editor.
MinWidth Sets the minWidth of the video element when it is inserted in the Rich Text Editor.
MaxWidth Sets the maxWidth of the video element when it is inserted in the Rich Text Editor.
Height Sets the default height of the video when it is inserted in the Rich Text Editor.
MinHeight Sets the minHeight of the video element when it is inserted in the Rich Text Editor.
MaxHeight Sets the maxHeight of the video element when it is inserted in the Rich Text Editor.
SaveUrl Provides URL to map the action result method to save the video.
Path Specifies the location to store the video.
EnableResize Sets the resizing action for the video element.
ResizeByPercent Sets the percentage values for the video element with the resizing action.

Configure video tool in the toolbar

To include the video tool in the Rich Text Editor, you can add the toolbar item Video to the RichTextEditorToolbarSettings.Items property.

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

@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
    <RichTextEditorToolbarSettings Items="@Items" />
</SfRichTextEditor>

@code {
    private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
    {
        new ToolbarItemModel() { Command = ToolbarCommand.Video }
    };
}

Insert video from web

To insert a video from the hosted link or local machine, you should enable the video tool on the editor’s toolbar. By default, the video tool opens the dialog, allowing you to insert a video as an embedded URL. You can switch to a web URL to insert the video file from the online source.

Insert from web URL

By default, the video tool opens the video dialog, allowing you to insert an embedded URL.

Blazor RichTextEditor insert audio from web

Upload and insert video

In the video dialog, by using the browse option, 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 [RichTextEditorVideoSettings]https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.RichTextEditor.RichTextEditorVideoSettings.html), the video will be converted into Blob url or Base64 and inserted inside the Rich Text Editor.

Restrict video upload based on size

Using the Rich Text Editor FileUploading event, you can restrict the video to upload when the given video size is greater than the allowed fileSize. Also, the video 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.

@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
    <RichTextEditorToolbarSettings Items="@Items" />
        <RichTextEditorEvents FileUploading="@onFileUploading"></RichTextEditorEvents>
        <RichTextEditorVideoSettings SaveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save" Path="../Files/"></RichTextEditorVideoSettings>
</SfRichTextEditor>
@code {
    private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
    {
        new ToolbarItemModel() { Command = ToolbarCommand.Video }
    };

    private void onFileUploading(FileUploadingEventArgs args)
    {
        var imgSize = 500000;
        var sizeInBytes = args.FilesData[0].Size;
        if ( imgSize < sizeInBytes ) {
            args.Cancel = true;
        }
    }
}

Server-side action

The selected video can be uploaded to the required destination using the controller action below. Map this method name in RichTextEditorMediaSettings.SaveUrl and provide required destination path through RichTextEditorMediaSettings.Path properties.

NOTE

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

@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
    <RichTextEditorToolbarSettings Items="@Items" />
        <RichTextEditorVideoSettings SaveUrl="api/Video/Save" Path="./Video/"></RichTextEditorVideoSettings>
</SfRichTextEditor>
@code {
    private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
    {
        new ToolbarItemModel() { Command = ToolbarCommand.Video }
    };

}
using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;

namespace VideoUpload.Controllers
{
    [ApiController]
    public class VideoController : ControllerBase
    {
        private readonly IWebHostEnvironment hostingEnv;

        public VideoController(IWebHostEnvironment env)
        {
            this.hostingEnv = env;
        }

        [HttpPost("[action]")]
        [Route("api/Video/Save")]
        public void Save(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (var file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string targetPath = hostingEnv.ContentRootPath + "\\wwwroot\\Video";
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

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

                        // Name which is used to save the video
                        filename = targetPath + $@"\{filename}";

                        if (!System.IO.File.Exists(filename))
                        {
                            // Upload a video, if the same file name does not exist in the directory
                            using (FileStream fs = System.IO.File.Create(filename))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            Response.StatusCode = 200;
                        }
                        else
                        {
                            Response.StatusCode = 204;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }
    }
}

Video save format

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

NOTE

By default, the files are saved in the 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>

Replacing video

Once a video file has been inserted, replace it using the Rich Text Editor RichTextEditorQuickToolbarSettings Replace option. Replace the video file either by using the embedded URL or the web URL and the browse option in the video dialog.

Blazor RichTextEditor embed video replace

Blazor RichTextEditor web video replace

Delete video

To remove a video from the Rich Text Editor content, select the video and click the “Remove” tool from the quick toolbar. It will delete the video from the Rich Text Editor content.

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.

Blazor RichTextEditor video delete

Dimension

Set the default Width, MinWidth, Height, and MinHeight of the video element when it is inserted in the Rich Text Editor using the RichTextEditorMediaSettings.Width, RichTextEditorVideoSettings.MinWidth, RichTextEditorMediaSettings.Height, and RichTextEditorVideoSettings.MinHeight properties.

Change the width and height of the RichTextEditorQuickToolbarSettings using the Change Size option. Once you click on the option, the video size dialog will open as follows. In that, specify the width and height of the video in pixels.

Blazor RichTextEditor video dimension

Display Position

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

NOTE

The default layoutOption property is set to Inline.

@using Syncfusion.Blazor.RichTextEditor;

<SfRichTextEditor>
    <RichTextEditorToolbarSettings Items="@Items" />
        <RichTextEditorVideoSettings LayoutOption="DisplayLayoutOptions.Break"></RichTextEditorVideoSettings>
        <p>
            The Rich Text Editor control is WYSIWYG ('what you see is what you get') editor that provides the best user experience to create and update the content.
            Users can format their content using standard toolbar commands.
        </p>
        <p><b> Key features:</b></p>
        <ul>
            <li><p> Provides &lt; IFRAME &gt; and &lt; DIV &gt; modes </p></li>
            <li><p> Capable of handling markdown editing.</p></li>
            <li><p> Contains a modular library to load the necessary functionality on demand.</p></li>
            <li><p> Provides a fully customizable toolbar.</p></li>
            <li><p> Provides HTML view to edit the source directly for developers.</p></li>
            <li><p> Supports third - party library integration.</p></li>
            <li><p> Allows preview of modified content before saving it.</p></li>
            <li><p> Handles images, hyperlinks, video, hyperlinks, uploads, etc.</p></li>
            <li><p> Contains undo / redo manager.</p></li>
            <li><p> Creates bulleted and numbered lists.</p></li>
        </ul>
</SfRichTextEditor>
@code {
    private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
    {
        new ToolbarItemModel() { Command = ToolbarCommand.Video }
    };
}

Resize video

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 RichTextEditorVideoSettings.EnableResize property.

NOTE

If the RichTextEditorVideoSettings.MinWidth and RichTextEditorVideoSettings.MinHeight properties are configured the video resizing does not shrink below the specified values.

Blazor RichTextEditor video resize

Rename video before inserting

By using the RichTextEditorVideoSettings property, you can 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.

Refer rename.cs controller file for configure the server-side.

@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
    <RichTextEditorToolbarSettings Items="@Items" />
        <RichTextEditorEvents FileUploadSuccess="@onFileUploadSuccess"></RichTextEditorEvents>
        <RichTextEditorVideoSettings SaveUrl="api/Video/Rename" Path="./Video/"></RichTextEditorVideoSettings>
</SfRichTextEditor>
@code {

    public string[] header { get; set; }

    private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
    {
        new ToolbarItemModel() { Command = ToolbarCommand.Video }
    };

    private void onFileUploadSuccess(FileUploadSuccessEventArgs args)
    {
        var headers = args.Response.Headers.ToString();
        header = headers.Split("name: ");
        header = header[1].Split("\r");

        // Update the modified video name to display a video in the editor.
        args.File.Name = header[0];
    }

}
using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;

namespace RenameVideo.Controllers
{
    [ApiController]
    public class VideoController : ControllerBase
    {
        private double x;
        private string videofileName;
        private readonly IWebHostEnvironment hostingEnv;

        public VideoController(IWebHostEnvironment env)
        {
            this.hostingEnv = env;
        }

        [HttpPost("[action]")]
        [Route("api/Vedio/Rename")]
        public void Rename(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (IFormFile file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string targetPath = hostingEnv.ContentRootPath + "\\wwwroot\\Video";
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

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

                        videofileName = filename;
                        string path = hostingEnv.WebRootPath + "\\Images" + $@"\{filename}";

                        // Rename a uploaded image file name
                        while (System.IO.File.Exists(path))
                        {
                            videofileName = "rteImage" + x + "-" + filename;
                            path = hostingEnv.WebRootPath + "\\Images" + $@"\rteImage{x}-{filename}";
                            x++;
                        }

                        if (!System.IO.File.Exists(path))
                        {
                            using (FileStream fs = System.IO.File.Create(path))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                                fs.Close();
                            }

                            // Modified file name shared through response header by adding custom header
                            Response.Headers.Add("name", videofileName);
                            Response.StatusCode = 200;
                            Response.ContentType = "application/json; charset=utf-8";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }
    }
}

Upload video with authentication

The Rich Text Editor control allows you to add additional data with the File Upload, which can 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.

NOTE

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

@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
    <RichTextEditorToolbarSettings Items="@Items" />
        <RichTextEditorEvents FileUploading="@onFileUploading"></RichTextEditorEvents>
        <RichTextEditorVideoSettings SaveUrl="api/Video/Save" Path="./Video/"></RichTextEditorVideoSettings>
</SfRichTextEditor>
@code {
    private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
    {
        new ToolbarItemModel() { Command = ToolbarCommand.Video }
    };

    private void onFileUploading(FileUploadingEventArgs args)
    {
        var accessToken = "Authorization_token";
        // adding custom Form Data
        args.CustomFormData = new List<object> { new { Authorization = accessToken } };
    }
}
using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;

namespace VideoUpload.Controllers
{
    [ApiController]
    public class VideoController : ControllerBase
    {
        private readonly IWebHostEnvironment hostingEnv;

        public VideoController(IWebHostEnvironment env)
        {
            this.hostingEnv = env;
        }

        [HttpPost("[action]")]
        [Route("api/Video/Save")]
        public void Save(IList<IFormFile> UploadFiles)
        {
            string currentPath = Request.Form["Authorization"].ToString();
            try
            {
                foreach (var file in UploadFiles)
                {
                    if (UploadFiles != null)
                    {
                        string targetPath = hostingEnv.ContentRootPath + "\\wwwroot\\Video";
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

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

                        // Name which is used to save the video
                        filename = targetPath + $@"\{filename}";

                        if (!System.IO.File.Exists(filename))
                        {
                            // Upload a video, if the same file name does not exist in the directory
                            using (FileStream fs = System.IO.File.Create(filename))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            Response.StatusCode = 200;
                        }
                        else
                        {
                            Response.StatusCode = 204;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }
    }
}

See also