How to add an image to CKEditor 5 using ASP.NET Core Razor Pages

ClassicEditor.create(document.querySelector('#News_Body'),
{
  language: 'fa',
  ckfinder: {
    uploadUrl: 'URL'
  }
}).catch(error =>
  {
    console.error(error);
  });

I'm working on a project where I need to create a Razor Page that allows users to upload images to the server using CKEditor. Can you provide me with a sample code for this functionality?

Answer №1

Is it possible to upload an image in CKEditor 5 using asp.net core razor Pages?

To achieve the above requirement, you can refer to the example below.

JavaScript code

@section scripts{
    <script src="https://cdn.ckeditor.com/ckeditor5/22.0.0/classic/ckeditor.js"></script>

    <script>
        ClassicEditor
            .create(document.querySelector('#News_Body'),
                {
                    language: 'fa',
                    ckfinder: { uploadUrl: '/index/UploadImage' }
                })
            .catch(error => { console.error(error); }); 
    </script>
}

Page model class and handler

[IgnoreAntiforgeryToken]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {

    }

    public async Task<JsonResult> OnPostUploadImage([FromForm]IFormFile upload)
    {
        if (upload.Length <= 0) return null;

        //your custom code logic here

        //1)check if the file is image

        //2)check if the file is too large

        //etc

        var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();

        //save file under wwwroot/CKEditorImages folder

        var filePath = Path.Combine(
            Directory.GetCurrentDirectory(), "wwwroot/CKEditorImages",
            fileName);

        using (var stream = System.IO.File.Create(filePath))
        {
            await upload.CopyToAsync(stream);
        }

        var url = $"{"/CKEditorImages/"}{fileName}";

        var success = new uploadsuccess
        {
            Uploaded = 1,
            FileName = fileName,
            Url = url
        };

        return new JsonResult(success);
    }
}

public class uploadsuccess
{
    public int Uploaded { get; set; } 
    public string FileName { get; set; }
    public string Url { get; set; }
}

Test Result

https://i.sstatic.net/OnGYS.png

Answer №2

the solution above worked perfectly for me. I simply made a change to the PATH in ckFinder

@section scripts{
    <script src="https://cdn.ckeditor.com/ckeditor5/22.0.0/classic/ckeditor.js"></script>

    <script>
        ClassicEditor
            .create(document.querySelector('#News_Body'),
                {
                    language: 'fa',
                    ckfinder: { uploadUrl: '/index/?handler=UploadImage' }
                })
            .catch(error => { console.error(error); }); 
    </script>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The integration of Angular CLI with SCSS is no longer a separate process -

It seems like I might be overlooking something very straightforward here. After a fresh installation of angular-cli, I created a new website with SCSS. I input the SCSS in the global style.scss as well as some in a component SCSS file. However, when I se ...

Unable to access socket.io due to a 404 error

I've encountered an issue while setting up a node server to serve a web page using socket.io. Upon loading the page, I noticed the following error in the console: (index):6 GET http://localhost:3000/socket.io/socket.io.js which is then followed by ...

What is the best way to transfer a string to a different Vue component?

Within my project, I have a masterData.js file that serves as a repository for my master data. This file retrieves data from my mongo db and distributes it to various components of the project. To facilitate this process, I have implemented a function with ...

Insert HTML content into an iframe with a callback function

We are receiving information from the backend server and need to transfer it to an iframe. In order to accurately set the height of the iframe to match the content, we must wait for the content to be loaded into the iframe. However, this process may not ha ...

Managing numerous invocations of an asynchronous function

I have an imported component that triggers a function every time the user interacts with it, such as pressing a button. Within this function, I need to fetch data asynchronously. I want the function calls to run asynchronously, meaning each call will wait ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

How do I retrieve an index value from an array in GraphQL?

I am seeking a solution for obtaining the index of an array item that is not returned by downstream response. Let's consider my schema: schema: type Cart { items: [Item] } type Item { name: String index: Int } When the data comes in, it lo ...

Exploring Node.js: A Comparison of Promises and Callbacks Versus Synchronous

I have knowledge about Promises and Callbacks. However, I am curious to know, Is it considered good practice to use synchronous modules such as Sync, synchronize, etc.,? What are the appropriate scenarios or use cases for using Sync and in which scenario ...

Refresh jQuery CSS for active button whenever a different button is clicked

I want to enhance a group of buttons using jQuery. I aim to make the active button visually stand out so that users can easily identify it. These buttons are being created through a PHP foreach loop, as shown below: foreach($result as $row){ echo "< ...

Why is it important to avoid reassigning parameters in real-life situations? Can you provide an example of a problem that may arise from this practice?

Many inquiries focus on the best methods to follow the no-param-reassign linting rule, but there is a lack of requests to demonstrate the reasoning behind the rule. It is common to hear claims like 'Assigning values to variables defined as function p ...

Issue with identifying if an element has a specific class in jQuery

Utilizing bootstrap tabs, I wanted to execute some JavaScript functions when a LI element is clicked. However, I only want these functions to run conditionally based on whether the tab is already active or not. I attempted to create code that checks if th ...

The ASP.NET Membership Provider and the World Wide Web Services

I am currently developing a web application using ASP.NET Membership Provider to manage user authentication and roles. Next, I need to develop a web service to offer asynchronous functionalities, and I must call web methods from various pages within my ap ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

New Update Required for Selenium Chrome Driver Version in ASP.NET Core Selenium Testing

Currently, I am encountering challenges with my Selenium tests failing both locally and on the DevOps Azure pipeline for Selenium testing. The root of the error seems to be a version discrepancy between the browser and driver being utilized. Despite atte ...

Error code 400 was received from the remote server, indicating a bad request

I am working on sending a request from our Windows form to the QuickBooks server, but I am encountering an error. Any assistance would be greatly appreciated. Here is the code snippet where I am attempting to make the request: var oAuthConsumerKey = "" ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

Storage of various Checkboxes using Local Storage

Currently, I have a modal where users can select checkboxes, and based on their selections, specific divs should appear on the main page. I am looking to implement local storage functionality to remember the checkbox states even after the page is reloaded ...

Is there a way to turn off vue.js transitions specifically for testing purposes?

I'm utilizing a vue.js component with the <transition> element for show/hide animations. However, I want to disable the animation for faster testing. How can I achieve this? The solution proposed is * { transition: none !important } in this lin ...

React throws a "ReferenceError: indexedDB is not defined" but surprisingly, it still manages to function properly

I utilized yarn to install idb-keyval By utilizing the following code, I imported it: import { set } from 'idb-keyval'; Then, I assigned a value to a variable using the following code snippet: set('hello', 'world'); Althou ...

Implementing AJAX windows while running code in the background with ASP.NET

Currently, I am working on a form that spans across three pages, and I need to gather data from users. As they move from one page to another, I want to implement an ajax window that will display a message like "saving your data." At the same time, I also ...