How To Upload Images In A Rich Text Editor

Introduction

In this article, I've used a web API for supporting databases and uploading images in a rich text editor.

What is a rich text editor?

The TinyMCE is a rich text editor that allows users to create user-formatted content within a user-friendly interface. The TinyMCE library is used for implementing a rich text editor in a project.

The TinyMCE rich text editor output is created in HTML. It includes tables, lists, images, text, and other elements, depending on your configuration. Users have complete control over the TinyMCE rich text editor, and we can extend its plugins, customizations, and functionality.

How to implement the rich text editor in a project

Step 1

To download the TinyMCE text editor from the TinyMCE official website.

Extract the TinyMCE folder and copy the TinyMCE folder under the js folder. Then, paste it into the js folder of the www root folder.

Step 2

Add the library into the layout file.

<script src="~/js/tinymce/tinymce.min.js" referrerpolicy="original"></script>

Step 3

Create a ViewEditor class from the ViewModels folder. In a class, we make properties.

namespace richtexteditorAPP.ViewModels
{
    public class ViewEditor
    {
        public Guid id { get; set; }
        public string title { get; set; }
        public string message { get; set; }
        public IFormFile editorimage { get; set; }
    }
}

Step 4

Create a HttpHelper class from the logic folder. In this class, we create a PostData function to insert data into the database. In this function, we convert string data into JSON format and stored the response in the response message variable then return the result.

using Newtonsoft.Json;

namespace richtexteditorAPP.Logics
{
    public class HttpHelper
    {
        private readonly HttpClient _httpClient;
        public HttpHelper(HttpClient httpclient)
        {
            this._httpClient = httpclient;
        }
        public bool POSTData(object data, string url)
        {
            using (var content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage result = _httpClient.PostAsync(url, content).Result;
                if (result.IsSuccessStatusCode)
                    return true;
                string returnValue = result.Content.ReadAsStringAsync().Result;
                throw new Exception($"Failed to POST data: ({result.StatusCode}): {returnValue}");
            }
        }
    }
}

Step 5

Create a controller from the controller folder and in a controller, we call the Web API to upload an image. Here we create the HttpPost Add message method for calling the Web API Post method.

The TinyMceUpload function helps to post an image into the editor. The upload to the server method helps to store images in the database.

using Microsoft.AspNetCore.Mvc;
using richtexteditorAPP.Logics;
using richtexteditorAPP.Models;
using richtexteditorAPP.ViewModels;
using System.Text.Json;

namespace richtexteditorAPP.Controllers
{
    public class Editor : Controller
    {
        private readonly HttpClient httpClient;
        private readonly HttpHelper httphelper;
        public Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnviroment { get; set; }
        public richtexteditorAPP.Models.Editor message { get; set; }
        public Editor(HttpClient _httpClient, HttpHelper _httphelper, Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnviroment)
        {
            this.httpClient = _httpClient;
            this.httphelper = _httphelper;
            this.hostingEnviroment = hostingEnviroment;
        }
        
        public IActionResult AddMessage()
        {
            return View();
        }
        public IActionResult TinyMceUpload(IFormFile file)
        {
            var location = UploadImageToServer(file);
            return Json(new { location });

        }

        public string UploadImageToServer(IFormFile file)
        {
            var uniqueFileName = "";
            var fullFilePath = "";
            if (file != null)
            {
                var uploadfilepath = Path.Combine(hostingEnviroment.WebRootPath, "Images");
                uniqueFileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                fullFilePath = Path.Combine(uploadfilepath, uniqueFileName);
                file.CopyTo(new FileStream(fullFilePath, FileMode.Create));
            }
            return "/Images/" + uniqueFileName;
        }

        [HttpPost]
        public IActionResult AddMessage(ViewEditor p)
        {
            if (httphelper.POSTData(p, "https://localhost:7106/api/Editor"))
            {
                return RedirectToAction("Index");

            }
            return View();
        }
        public List<richtexteditorAPP.Models.Editor> Data { get; set; }
         public async Task<IActionResult> Index()
        {
            HttpResponseMessage responseMessage = httpClient.GetAsync("https://localhost:7106/api/Editor").Result;
            if (responseMessage.IsSuccessStatusCode)
            {
                var res = await responseMessage.Content.ReadAsStreamAsync();
                Data = await JsonSerializer.DeserializeAsync<List<richtexteditorAPP.Models.Editor>>(res);
            }
            return View(Data);
        }
    }
}

Step 6

Create a form with one input text and one text area, and add a script section at the end of the form.

<h2 style="margin-left:250px;">Add Message</h2>
<div class="container col-md-8">
<form enctype="multipart/form-data" method="post">
    <div class="mb-3">
    <label class="form-label">Title</label>
    <input type="text" name="title" id="title" class="form-control" >
   </div>
  <div class="mb-3">
    <label class="form-label">Message</label>
    <textarea name="message" id="message" class="form-control"></textarea>
  </div>
  <div class="btn-group" style="margin-top:20px;">
  <button type="submit" class="btn btn-primary">Post</button>
  </div>
</form>
</div>
@section Scripts{
    <script>
tinymce.init({
    selector: 'textarea#message',
    plugins: [
      'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',
      'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime',
      'media', 'table', 'emoticons', 'template', 'help'
    ],
    toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | ' +
      'bullist numlist outdent indent | link image | print preview media fullscreen | ' +
      'forecolor backcolor emoticons | help',
    menu: {
      favs: { title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons' }
    },
    menubar: 'favs file edit view insert format tools table help',
    content_css: 'css/content.css',
    images_upload_url: '/Editor/TinyMceUpload'
   });

</script>
}

In the script section, we call the TinyMCE text editor and also add plugins.

Output

Conclusion

The better advantage of a rich text editor is it allows to manipulate the text, images, list, tables, and others.

It's easy to change the size of the image.

It's easy to set the alignment of items.


Similar Articles