Skip to content
Advertisement

How upload image in CKEditor 5 With asp.net core razor Pages

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

I Have A Razor Page Ineed this Page UPload image to server by CKEditor give me a sample

Advertisement

Answer

How upload image in CKEditor 5 With asp.net core razor Pages

You can refer to the following example to achieve above requirement.

JS 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

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement