CKEDITOR 文件上传错误请求 400 错误

CKEDITOR File Upload Bad Request 400 Error

我正在使用带有文件浏览器和文件管理器插件的 ckEditor。当我配置 CKeditor 时我想要实现的目标我能够浏览某个文件夹中的文件..但是当我尝试通过它上传文件时我收到错误 400 Bad Request 可能是我需要做什么?

以下是我的代码

[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();
} );

请求处理程序 C# ASP.NET 核心 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);
        }

额外的插件代码:

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';
    
    
};

请帮帮我

这里是 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

根据您的测试请求的详细信息,您似乎配置并启用了防伪令牌验证。如果JavaScript客户端没有set/include请求中的token,会导致400 Bad Request错误。

要修复它,正如我在评论中提到的,我们可以将 IgnoreAntiforgeryToken 属性应用于操作方法 UploadFromEditor 以跳过防伪标记验证。

或者在请求头中设置token,使请求能够通过防伪token验证。

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