How to save the images and text from a rich text editor in the database?

Answer:

In our Blazor application, we have some limitations to send data from client-side applications to server-side applications. So, we have used blob URL for Rich Text Editor content images. If we wish to store the Rich Text Editor content with images in the database, we can convert the blob URL to Base64 string and store it in the database.

Index.razor

<EjsRichTextEditor Id="defalt_RTE" @ref="RTE" @bind-Value="@rteValue"> // Used for getting Rich Text Editor value

<ChildContent>

<RichTextEditorImageSettings SaveUrl="api/SampleData/Save">RichTextEditorImageSettings> // Used for convert base 64 string on server side

ChildContent>

EjsRichTextEditor>

SampleDataController.cs

using System.Text.RegularExpressions;

[HttpPost("[action]")]

public IActionResult Save(IList UploadFiles) // Triggered when you upload the images

{

………….

// Stored base64 string to global list

if (ImageInfo.Count == 0)

{

ImageInfo.Add(new RTEImage { imgName = UploadFiles[0].FileName, base64Img = base64String });

}

else if(!ImageInfo.Exists(x => x.imgName == UploadFiles[0].FileName))

{

ImageInfo.Add(new RTEImage { imgName = UploadFiles[0].FileName, base64Img = base64String });

}

return Content("");

}

[HttpPost("[Action]")]

public void Add([FromBody] RTEValue value) // Triggered when you click the button

{

htmlText = value.value; // Get the RTE value

string pattern = @".*?)"".*?src=""(?.*?)"".*?>"; // Regular Expression for getting image tag with source and alt attribute

Regex rx = new Regex(pattern);

foreach (Match m in rx.Matches(htmlText))

{

var imageName = m.Groups["alt"].Value;

var blobUrl = m.Groups["url"].Value;

var data = ImageInfo.Find(x => x.imgName.Contains(imageName)); // Find the corresponding base64 string

htmlText = htmlText.Replace(blobUrl, data.base64Img); //Replace blobURL to base64 string. Now, You can store this htmlText value to your database. It contains both images and content.

}

}


Find the sample to save the images and text from a rich text editor in the database from here.

Loader.
Up arrow icon