首页 > 解决方案 > CKEditor 5 使用自定义上传适配器上传图像

问题描述

我正在使用带有 Spring-Boot 后端的 Angular 11 实现 CKEditor 5。根据https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html ,我实现了一个自定义图像上传适配器。

在后端,我使用令牌实现了安全性。

上传工作正常。但是,图像的加载不起作用,它给出了 HTTP 401 错误。

如何自定义自定义适配器以使用令牌加载图像?

这是代码:

export class CustomUploadAdapter {
    public loader: any;
    public url: string;
    public xhr: XMLHttpRequest;
    public token: string;

    constructor(
        loader    
    ) {
        this.loader = loader;
    }

    upload() {

        return new Promise(async (resolve, reject) => {
            this.loader.file.then((file) => {
                this._initRequest();
                this._initListeners(resolve, reject, file);
                this._sendRequest(file);
            });
        });
    }

    abort() {
        if (this.xhr) {
            this.xhr.abort();
        }
    }

    _initRequest() {
        const xhr = (this.xhr = new XMLHttpRequest());
        xhr.open("POST", this.url, true);
        this.token = localStorage.getItem("access_token");
        this.token = localStorage.getItem("access_token");
        
        xhr.setRequestHeader("Authorization", 'Bearer ' + this.token);

        xhr.responseType = "json";
    }

    _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;

            if (!response || response.error) {
                return reject(
                    response && response.error ? response.error.message : genericErrorText
                );
            }

            resolve(
                response.urls
            );
        });

        if (xhr.upload) {
            xhr.upload.addEventListener("progress", (evt) => {
                if (evt.lengthComputable) {
                    loader.uploadTotal = evt.total;
                    loader.uploaded = evt.loaded;
                }
            });
        }
    }

    _sendRequest(file) {
        const data = new FormData();

        data.append("file", file);

        this.xhr.send(data);
    }
}

export class Component implements OnInit {

  @ViewChild('ckeditor', { static: false })
  ckeditor: any;

  public configCkeditor = Ckeditor5Util.configCkeditor; //configs...
   ...
   public onReady(editor) {
    editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
      return new CustomUploadAdapter(loader);
    };
    ...
   }
   ...
}

html {
...
<ckeditor [editor]="editor" (ready)="onReady($event)" formControlName="texto" debounce="500"
      [config]="configCkeditor"></ckeditor>
...
}

标签: angularckeditorckeditor5

解决方案


推荐阅读