locked
upload image with ckeditor in mvc core RRS feed

  • Question

  • User1431049546 posted

    Hello . I want to upload a picture through CKeditor, but I have a 400 error. Thank you for guidance.

    config file :

    CKEDITOR.editorConfig = function (config) { // Define changes to default configuration here. For example: // config.uiColor = '#AADC6E'; config.contentsLangDirection = 'rtl'; config.language = 'fa'; config.filebrowserImageUploadUrl = './ImageUpload' ; config.toolbar = 'MyToolbar'; config.toolbar_MyToolbar = [ { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates'] }, { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-', 'SpellChecker', 'Scayt'] }, { name: 'forms', items: ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'] }, { name: 'links', items: ['Link', 'Unlink', 'Anchor'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, '/', { name: 'insert', items: ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'] }, { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] } ]; };
    
    

    view code :

    <div class="container text-right dirrtl"> <div class="row"> <div class="col-md-8"></div> </div> </div>
    
    @section scripts{
    
    <script src="//cdn.ckeditor.com/4.11.4/standard/ckeditor.js"></script> <script> CKEDITOR.replace('description', { customConfig: '/js/Config.js' }); </script>
    
    }

    Saturday, June 15, 2019 7:03 AM

Answers

  • User-821857111 posted

    A 400 error is usually returned by ASP.NET if your request fails verification. This most often occurs if you make a POST request using AJAX, but forget to include the verification token that gets generated by the BeginForm HTML helper or the form tag helper if you are using ASP.NET Core, or you haven't generated a request token but the action/handler method expects one. 

    It's difficult to tell if this applies to your issue because you haven't provided any details on how you are trying to upload the image or process it.

    More details on the verification token can be found here: https://www.learnrazorpages.com/security/request-verification. The post is about Razor Pages on .NET Core, but the principal is the same for MVC.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 17, 2019 11:51 AM

All replies

  • User-821857111 posted

    A 400 error is usually returned by ASP.NET if your request fails verification. This most often occurs if you make a POST request using AJAX, but forget to include the verification token that gets generated by the BeginForm HTML helper or the form tag helper if you are using ASP.NET Core, or you haven't generated a request token but the action/handler method expects one. 

    It's difficult to tell if this applies to your issue because you haven't provided any details on how you are trying to upload the image or process it.

    More details on the verification token can be found here: https://www.learnrazorpages.com/security/request-verification. The post is about Razor Pages on .NET Core, but the principal is the same for MVC.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 17, 2019 11:51 AM
  • User1431049546 posted

    Thank you so much

    I built an Area "Admin" and a Controller then in Index Action :

            public IActionResult Index()
            {
                return View();
            }

    and View Index :

    <div class="container text-right dirrtl">
    
        <div class="row">
    
            <div class="col-md-8">
    
    
                <textarea id="description" rows='7'></textarea>
            </div>
        </div>
    </div>
    
    @section scripts{
    
        <script src="//cdn.ckeditor.com/4.11.4/standard/ckeditor.js"></script>
    
        <script>
            CKEDITOR.replace('description', {
                customConfig: '/js/Config.js'
            });
    
        </script>
    
    }

    and Then my action UploadImage :

             [HttpPost]
             [ValidateAntiForgeryToken]
     public IActionResult UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor, string langCode)
            {
                if (upload.Length <= 0) return null;
    
                var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();
    
    
    
                var path = Path.Combine(
                    _hostingEnvironment.WebRootPath, "MyImages",
                    fileName);
    
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    upload.CopyTo(stream);
    
                }
    
    
    
                var url = $"{"/MyImages/"}{fileName}";
    
    
                return Json(new { uploaded = true, url });
            }
    

    and config.js :

    CKEDITOR.editorConfig = function (config) {
        // Define changes to default configuration here. For example:
        // config.uiColor = '#AADC6E';
        config.contentsLangDirection = 'rtl';
        config.language = 'fa';
        config.filebrowserImageUploadUrl = './uploadimage' ;
        config.toolbar = 'MyToolbar';
        
    
        config.toolbar_MyToolbar =
            [
                { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates'] },
                { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
                { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-', 'SpellChecker', 'Scayt'] },
                { name: 'forms', items: ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'] },
                { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'] },
                { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
                { name: 'colors', items: ['TextColor', 'BGColor'] },
                '/',
                { name: 'insert', items: ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'] },
                { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'] },
                { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] }
    
            ];
    };

    Tuesday, June 18, 2019 6:47 PM
  • User-821857111 posted

    I still can't see any code for uploading the image. Are you using a jQuery $.post ? 

    Tuesday, June 18, 2019 7:56 PM
  • User1431049546 posted

    no , for uploading via config file

    Wednesday, June 19, 2019 5:01 AM
  • User-821857111 posted

    I don't understand what a config file has to do with this. But in any event, your upload ActionResult expects an antiforgery token. The 400 result suggests that one is not being passed when the upload is attempted. You haven't shown your upload form, but I suspect that you are not generating an antiforgery token

    Wednesday, June 19, 2019 6:30 AM
  • User1431049546 posted

    yes

    I have added these codes but it is not correct

    in view:

    @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
    @functions{
        public string GetAntiXsrfRequestToken()
        {
            return Xsrf.GetAndStoreTokens(Context).RequestToken;
        }
    }
    

    and in config.js :

    CKEDITOR.editorConfig = function (config) {
        // Define changes to default configuration here. For example:
        // config.uiColor = '#AADC6E';
     
        config.contentsLangDirection = 'rtl';
        config.language = 'fa';
        config.filebrowserImageUploadUrl = 'uploadImage';
        config.toolbar = 'MyToolbar';
        config.fileTools_requestHeaders = {
            'X-CSRFToken': '{{ @GetAntiXsrfRequestToken() }}'
        },
           

    Wednesday, June 19, 2019 7:26 AM
  • User-821857111 posted

    In ASP.NET Core, the name of the header should be RequestVerificationToken, unless you have specified something else in Startup.

    Wednesday, June 19, 2019 7:47 AM
  • User1431049546 posted

    I changed code to below and It 's worked :

     fileTools_requestHeaders: {
                        "RequestVerificationToken": '@GetAntiXsrfRequestToken()'},

    Thank you very much

    Wednesday, June 19, 2019 7:49 AM
  • User1431049546 posted

    One question is, photos are now stored in the myimage folder and their address is in ckeditor

    "<p><img alt=\"\" src=\"/MyImages/d7fb3201-91d6-4adb-98ed-5bd5408f51d5.jpg\" style=\"height:1280px; width:892px\" />kkkkkk</p>\r\n\r\n<p>gggg</p>\r\n\r\n<p>&nbsp;</p>\r\n"

    If I want to save the URL of the ckeditor to the server, what should I do?

    Should I search the entire text for the name of the photo and save any image in the database?

    Wednesday, June 19, 2019 12:26 PM