ckedit5 自定义上传图片

class MyUploadAdaper {
  constructor(loader) {
    this.loader = loader
  }
  _sendRequest( file ) {
      const data = new FormData();
      data.append( 'file', file );
      this.xhr.send( data );
  }
  _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( {
              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 => {
              console.log("progress");
              if ( evt.lengthComputable ) {
                  loader.uploadTotal = evt.total;
                  loader.uploaded = evt.loaded;
              }
              console.log(loader.uploaded+"/"+loader.uploadTotal);
          } );
      }
  }
  _initRequest() {
    const xhr = this.xhr = new XMLHttpRequest();
    xhr.open( 'POST', '/admin/upload', true );
    xhr.responseType = 'json';
  }
  upload() {
    return this.loader.file
        .then( file => new Promise( ( resolve, reject ) => {
            this._initRequest();
            this._initListeners( resolve, reject, file );
            this._sendRequest( file );
        } ) );
  }
  abort() {
    if ( this.xhr ) {
          this.xhr.abort();
      }
  }
}
...
...

ClassicEditor
        .create( document.querySelector( "#editor" ), {
          language: 'zh-cn',
        } )
        .then(editor => {
          console.log(editor)
          this.editor = editor;
          editor.plugins.get('FileRepository').createUploadAdapter = ( loader ) => {
            return new MyUploadAdaper(loader);
          };
        })
        .catch( error => {
            console.error( error );
        } );

你可能感兴趣的:(ckedit5 自定义上传图片)