c# - 如何在 ASP.Net Core - CKEDITOR 5 上使用自定义上传适配器?

标签 c# asp.net-core ckeditor ckeditor5

我为基于 ASP.Net Core 的博客安装了 CKEDITOR 5,以上传包含图像和一些 html 样式的博客。但我想将文件上传到我的 IIS 静态文件中的某个目录,例如“wwwroot/bloguploads/”,这可能吗?

在创建编辑器时我应该更改哪些参数来更改上传操作?

最佳答案

这是我的项目 cshtml 文件

<div class="tab-panels">
    <!-- The toolbar will be rendered in this container. -->
    <div id="toolbar-container"></div>

    <!-- This container will become the editable. -->
    <div id="desEditor"></div>
    @Html.HiddenFor(model => model.Description);
</div><!-- .tab-panels -->

JavaScript

class MyUploadAdapter {
        constructor(loader) {
            // The file loader instance to use during the upload.
            this.loader = loader;
            this.url = '/VehicleKey/DocUploadImage';
        }

        // Starts the upload process.
        upload() {
            return this.loader.file.then(file => new Promise((resolve, reject) => {
                this._initRequest();
                this._initListeners(resolve, reject, file);
                this._sendRequest(file);
            }));
        }

        // Aborts the upload process.
        abort() {
            if (this.xhr) {
                this.xhr.abort();
            }
        }

        _initRequest() {
            const xhr = this.xhr = new XMLHttpRequest();

            xhr.open('POST', this.url, true);
            xhr.responseType = 'json';
        }

        // Initializes XMLHttpRequest listeners.
        _initListeners(resolve, reject, file) {
            const xhr = this.xhr;
            const loader = this.loader;
            const genericErrorText = `Couldn't upload file: ${file.name}.`;

            xhr.addEventListener('error', () => reject(genericErrorText));
            xhr.addEventListener('abort', () => reject());
            xhr.addEventListener('load', () => {
                const response = xhr.response;

                // This example assumes the XHR server's "response" object will come with
                // an "error" which has its own "message" that can be passed to reject()
                // in the upload promise.
                //
                // Your integration may handle upload errors in a different way so make sure
                // it is done properly. The reject() function must be called when the upload fails.
                if (!response || response.error) {
                    return reject(response && response.error ? response.error.message : genericErrorText);
                }

                // If the upload is successful, resolve the upload promise with an object containing
                // at least the "default" URL, pointing to the image on the server.
                // This URL will be used to display the image in the content. Learn more in the
                // UploadAdapter#upload documentation.
                resolve({
                    default: response.url
                });
            });

            // Upload progress when it is supported. The file loader has the #uploadTotal and #uploaded
            // properties which are used e.g. to display the upload progress bar in the editor
            // user interface.
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', evt => {
                    if (evt.lengthComputable) {
                        loader.uploadTotal = evt.total;
                        loader.uploaded = evt.loaded;
                    }
                });
            }
        }

        // Prepares the data and sends the request.
        _sendRequest(file) {
            // Prepare the form data.
            const data = new FormData();

            data.append('upload', file);

            // Important note: This is the right place to implement security mechanisms
            // like authentication and CSRF protection. For instance, you can use
            // XMLHttpRequest.setRequestHeader() to set the request headers containing
            // the CSRF token generated earlier by your application.

            // Send the request.
            this.xhr.send(data);
        }
    }

    function MyCustomUploadAdapterPlugin(editor) {
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
            return new MyUploadAdapter(loader);
        };
    }

    DecoupledEditor.create(document.querySelector('#desEditor'), {
        extraPlugins: [MyCustomUploadAdapterPlugin]
    })
        .then(editor => {
            const toolbarContainer = document.querySelector('#toolbar-container');

            toolbarContainer.appendChild(editor.ui.view.toolbar.element);
        })
        .catch(error => {
            console.error(error);
        });

    document.getElementById("btnSubmitKey").addEventListener("click", (e) => {
        const richText = document.getElementById('desEditor').innerHTML;

        document.getElementById('Description').value = richText;
    });

Controller .cs

public async Task<JsonResult> DocUploadImage()
        {
            try
            {
                var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "images/vehicle-key");
                var filePath = Path.Combine(uploads, "rich-text");
                var urls = new List<string>();

                //If folder of new key is not exist, create the folder.
                if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);

                foreach (var contentFile in Request.Form.Files)
                {
                    if (contentFile != null && contentFile.Length > 0)
                    {
                        await contentFile.CopyToAsync(new FileStream($"{filePath}\\{contentFile.FileName}", FileMode.Create));
                        urls.Add($"{HttpContext.Request.Host}/rich-text/{contentFile.FileName}");
                    }
                }

                return Json(urls);
            }
            catch (Exception e)
            {
                return Json(new { error = new { message = e.Message } });
            }
        }

您可以访问CKEditor网站以引用更多信息。 有很多例子。您应该仔细阅读。

关于c# - 如何在 ASP.Net Core - CKEDITOR 5 上使用自定义上传适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446497/

相关文章:

javascript - 自定义CKEditor链接插件

c# - 管理 NuGet 包将 jquery 恢复到旧版本

c# - 如何将 xmldocument 保存到流中

c# - 复制加密算法

c# - 比较数据表的有效方法

asp.net-core - 使用 ASP.NET Core 中间件时如何处理 global.asax 文件中的所有事件

asp.net-core - 在哪里可以找到 ASP.NET Core 2 源代码?专用于 Microsoft.AspNetCore.Authentication.OpenIdConnect

asp.net - 没有配置身份验证处理程序来处理方案 : Automatic

javascript - CKEDITOR5如何插入youtube视频

jquery - 如何在销毁后重新初始化ckeditor而不重新加载页面