Search code examples
c#asp.net-core-mvcckeditor

How to upload image in CkEditor in ASP.NET Core MVC project?


I'm new to CkEditor, I've successfully integreted and customized the editor to my page but I can't upload images. In CkEditor documentation I found They using a PhP script to upload file but i'm not sure how can I add this to my ASP.NET MVC project.


Solution

  • follow my way step by step:

    first of all, add this to your layout:

    @RenderSection("scripts", required: false)
    

    then add this to your view:

    @section scripts{
    <script src="https://cdn.ckeditor.com/4.10.1/standard/ckeditor.js"></script>
        <script>
    
            CKEDITOR.replace('textarea's name', {
                customConfig: '/js/CustomConfig.js'
            });
    
        </script>
    }
    

    you can see I'm using CDN and CKeditor version 4.10.1. CustomConfig.js is a Custom javascript file you can create it in your project. in CustomConfig.js add this codes:

    CKEDITOR.editorConfig = function (config) {   
        config.removeDialogTabs = 'image:advanced;image:Link;link:advanced;link:upload';   
        config.filebrowserImageUploadUrl = '/Home/UploadImage' //Action for Uploding image  
    };
    

    finally in Action use this codes:

            [HttpPost]
            public ActionResult UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor, string langCode)
            {                  
                if (upload.Length <= 0 ) return null;
                if (!upload.IsImage())
                {
                    var NotImageMessage = "please choose a picture";
                    dynamic NotImage = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + NotImageMessage + "\"}}");
                    return Json(NotImage);
                }
    
                var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();
    
                Image image = Image.FromStream(upload.OpenReadStream());
                int width = image.Width;
                int height = image.Height;
                if ((width > 750) || (height > 500))
                {
                    var DimensionErrorMessage = "Custom Message for error"
                    dynamic stuff = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + DimensionErrorMessage + "\"}}");
                    return Json(stuff);
                }
    
                if (upload.Length > 500 * 1024)
                {
                    var LengthErrorMessage = "Custom Message for error";
                    dynamic stuff = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + LengthErrorMessage + "\"}}");
                    return Json(stuff);                
                }
    
                var path = Path.Combine(
                    Directory.GetCurrentDirectory(), "wwwroot/images/CKEditorImages",
                    fileName);
    
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    upload.CopyTo(stream);
    
                }
    
                var url = $"{"/images/CKEditorImages/"}{fileName}";
                var successMessage = "image is uploaded successfully";
                dynamic success = JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}");
                return Json(success);
            }
    

    IsImage() is an extesion method for checking image:

        public static class ImageValidator
        {
            public static bool IsImage(this IFormFile file)
            {
                try
                {
                    var img = System.Drawing.Image.FromStream(file.OpenReadStream());
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }