首页 > 解决方案 > 在 CkEditor 中获取选定的文件并添加自定义上传按钮

问题描述

  1. 我在角度 5 中使用 ngx-ckeditor: "0.4.0"。
  2. 我要上传图片并添加自定义上传按钮
  3. 下面是我的html。

    <ck-editor 
              #ckeditor 
              name="html_template" 
              [(ngModel)]="mailModel.html_template" 
              [config]="ckEditorConfig">
    </ck-editor>
    
  4. 这是我的组件代码。

    this.ckEditorConfig = {
       filebrowserBrowseUrl : '/application/crm/distribution-list/create-mail',
       filebrowserUploadUrl : 'http://192.168.0.107:8000/api/crm/v1.0/crm-distribution-library-files',
       fileTools_requestHeaders :{
          'X-Requested-With': 'XMLHttpRequest',
          Authorization: 'Bearer ' + localStorage.getItem('access_token')
       },
       filebrowserUploadMethod : 'xhr',
       removeButtons: 'Forms,Iframe,Blocks,Subscript,Superscript,Maximize,Undo',
    };
    
  5. 使用此代码,我无法获取图像并且无法传递我的自定义标头。

我想获取选定的图像并添加自定义“上传图像”按钮。

标签: angularjsckeditorangular5

解决方案


下面是在 CkEditor 中添加自定义按钮的代码

@ViewChild('ckeditor') ckeditor: CKEditorComponent;

ngAfterViewInit(): void {
    this._addImageUploadBtn();
}

_addImageUploadBtn() {
    const editor = this.ckeditor && this.ckeditor.instance;
    if (!editor) {
      return;
    }
    var that = this;
    editor.ui.addButton('uploadImage', {
        icon: 'https://img.icons8.com/ios/50/000000/image.png',
        label: 'Upload Image',
        command: 'uploadImage',
        toolbar: 'insert'
      });
    editor.addCommand('uploadImage', {
      exec: function(editor: any) {
        // Remove img input.
        [].slice.apply(document.querySelectorAll('.ck-editor-upload-img')).forEach((img: any) => {
          img.remove();
        });
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('class', 'ck-editor-upload-img');
        input.style.display = 'none';
        input.addEventListener('change', e => {
            const file = (e.target as HTMLInputElement).files[0];
            if (file) {
               console.log(file);
               // Do Stuff
            }
          },
          false
        );
        document.body.appendChild(input);
        input.click();
      }
    });
  }

在这里,您可以获得选定的图像文件,并获得自定义按钮点击。


推荐阅读