Search code examples
angularjsckeditorangular5

get selected file in CkEditor & add custom upload button


  1. i am using ngx-ckeditor: "0.4.0" in angular 5.
  2. i want upload image & add custom upload button
  3. below is my html.

    <ck-editor 
              #ckeditor 
              name="html_template" 
              [(ngModel)]="mailModel.html_template" 
              [config]="ckEditorConfig">
    </ck-editor>
    
  4. here is my component code.

    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. with this code i am not able to get image & can't pass my custom header.

i want to get selected image & add custom 'Upload Image' button.


Solution

  • below is the code for add custom button in 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();
          }
        });
      }
    

    here you get the selected image file, and also get custom button click.