简体   繁体   中英

CKEDITOR File Upload Bad Request 400 Error

I am using ckEditor with the file browser, filemanager plugin in it. What i am trying to achieve when i configure the CKeditor I am able to browse the file in a certain folder .. but when i try to upload the file through it I am getting an error of 400 Bad Request may be there is something which I need to do ?

Following is my code

[HttpPost]
  CKEDITOR.replace('content_editor',{
            customConfig: '/assets/back/dist/plugins/ckeditor/config.js',
            "imageBrowser_listUrl" : "/webmaster/files/browser"
        });

        CKEDITOR.on('fileUploadRequest', function (evt) {
        
  var fileLoader = evt.data.fileLoader,
        formData = new FormData(),
        xhr = fileLoader.xhr;

    xhr.open( 'PUT', fileLoader.uploadUrl, true );
    formData.append( 'upload', fileLoader.file, fileLoader.fileName );
    fileLoader.xhr.send( formData );

    // Prevented the default behavior.
    evt.stop();
} );

Request Handler C# ASP.NET CORE 3.1

 public async Task<IActionResult> UploadFromEditor([FromForm]IFormFile upload)
        {
            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/uploads/images/conten_images",
                fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                upload.CopyTo(stream);

            }

            var url = $"{"/uploads/images/CKEditorImages/"}{fileName}";
            var successMessage = "image is uploaded successfully";
            dynamic success = await Task.Run(() => JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}"));
            return Json(success);
        }

Extra Plugins code :

CKEDITOR.editorConfig = function( config ) {
    config.filebrowserBrowseUrl = '/assets/back/dist/ckeditor/plugins/imagebrowser/browser/browser.html'
    config.filebrowserUploadUrl = '/webmaster/files/UploadFromEditor';
    config.extraPlugins = 'filetools';
    config.extraPlugins = 'uploadimage';
    config.extraPlugins = 'popup';
    config.extraPlugins = 'imagebrowser';
    config.filebrowserUploadMethod = 'xhr';
    
    
};

请求详细信息

Please help me out here

here are the headers :

XHRPOSThttps://localhost:5001/webmaster/files/UploadFromEditor
[HTTP/2 400 Bad Request 73ms]

    
POST
    https://localhost:5001/webmaster/files/UploadFromEditor
Status400
Bad Request
VersionHTTP/2
Transferred85.50 KB (0 B size)

        
    content-length
        0
    date
        Tue, 03 Nov 2020 09:13:50 GMT
    server
        Kestrel
    X-Firefox-Spdy
        h2
        
    Accept
        */*
    Accept-Encoding
        gzip, deflate, br
    Accept-Language
        en-US,en;q=0.5
    Connection
        keep-alive
    Content-Length
        86268
    Content-Type
        multipart/form-data; boundary=---------------------------1063707225330149515660008029
    Cookie
        .AspNetCore.Session=CfDJ8ERqQf6e11lCnNAhOo0wjyavEQJqEJ7gsv1MXMI4QwPk9Px8mznruNuZcxnmuYGnGjs1GtOWQI4DVCXYKd%2FRbNNo62%2FtopzHy%2FxaW87rvNE13QikL84JT0m32Ie1LWSZR3AkxYAE5p4U7TEpN5FccezCSMDeUR9geLW3lSjFIJD4; .AspNetCore.Antiforgery.J7MIrShXchg=CfDJ8ERqQf6e11lCnNAhOo0wjyYadzIaShP7Nt-bl6orx5lTMtnVoGxw8noimjE32qvhp_f96p2Hx4_zK8hzdRIz12615ZdyisBTz6X9HPA39cgIvRTjmWmrWNcLlm4S2MvPAQrG9hofg1ANinWAOwKIyXc; ckCsrfToken=8qZ4KEfRjaBWRmI6coRoRbJrZd8DgYG18gAz86eN; .AspNetCore.Antiforgery.XfkU3LYWHPY=CfDJ8NfGIpF9PVtNgLP3wXt3ZoscmmPZ8ZskVSbYiI69p4lPZYB3mt9mFEqRuOV0Ajfi2f8NNbjcyEHtfta7RlEHTBhXdRfPonXD1sN2EIS2BvcjZCrN8sJXN4UMo_JlolirVt3VIcCTm-wGAtIzGq0150w
    Host
        localhost:5001
    Origin
        https://localhost:5001
    Referer
        https://localhost:5001/webmaster/News/Create
    TE
        Trailers
    User-Agent
        Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0
    X-Requested-With
        XMLHttpRequest

Cookie “.AspNetCore.Antiforgery.XfkU3LYWHPY” will be soon treated as cross-site cookie against “https://localhost:5001/webmaster/files/UploadFromEditor” because the scheme does not match. UploadFromEditor
Source map error: Error: request failed with status 404
Resource URL: https://localhost:5001/assets/back/dist/bootstrap/js/bootstrap.min.js
Source Map URL: bootstrap.min.js.map

Based on the details about your test request, it seems that you configured and enabled antiforgery token validation. If JavaScript client not set/include the token in request, which would cause 400 Bad Request error.

To fix it, as I mentioned in comment, we can apply IgnoreAntiforgeryToken Attribute to action method UploadFromEditor to skip antiforgery token validation.

Or set the token in request header to make the request can pass antiforgery token validation.

https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1#javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM