【问题标题】:image src get lost when submitted in ckeditor5在 ckeditor5 中提交时图像 src 丢失
【发布时间】:2020-09-16 11:47:58
【问题描述】:

我在ckeditor5在线文档之后使用了简单的自定义MyUploadAdapter。

图像从复制粘贴和文件上传对话框中显示,并上传到服务器。但是一旦点击保存textarea内容到我的服务器,图片src是空的,如图:

<figure class="image"><img></figure>

<figure class="image"><img src="" alt="16 Days of Activism | The Rose Campaign - Women in Crisis"></figure>

我正在使用的库: https://cdn.ckeditor.com/ckeditor5/19.0.0/classic/ckeditor.js

代码如下:

function synchValues()
{
/*
    for(var instanceName in CKEDITOR.instances)
        CKEDITOR.instances[instanceName].updateElement();
CKEDITOR.on('instanceReady', function(){
   $.each( CKEDITOR.instances, function(instance) {
    CKEDITOR.instances[instance].on("change", function(e) {
        for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();
    });
   });
});


    document.getElementById('editor').value = editor.getData();
*/



$('textarea.editor').each(function () {
   var $textarea = $(this);
   $textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
});


    return true;
}



function MyCustomUploadAdapterPlugin( editor ) {

    editor.plugins.get( 'FileRepository' ).createUploadAdapter = ( loader ) => {
        // Configure the URL to the upload script in your back-end here!
        return new MyUploadAdapter( loader );
    };
}

let editor;

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        extraPlugins: [ MyCustomUploadAdapterPlugin ],


        styles: [
            // This option is equal to a situation where no style is applied.
            'full',

            'side',

            // This represents an image aligned to the left.
            'alignLeft',

            'alignCenter',

            // This represents an image aligned to the right.
            'alignRight'
        ],

        image: {
            upload:  {
                types: ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'mp3', 'mp4', 'm4v', 'm4a', 'm1v', 'm2v', 'mp2', 'mpa', 'mpe', 'mpeg', 'mpg', 'mpv2', 'wav', 'pdf']
                // Image upload feature options.
            }
        }
    } )
    .then( newEditor => {
        console.log( 'Editor was initialized', newEditor );
        editor = newEditor;
    } )
    .catch( error => {
        console.log( error );
    } );

Here is the upload class:

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


    // Initializes the XMLHttpRequest object using the URL passed to the constructor.
    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();

        // Note that your request may look different. It is up to you and your editor
        // integration to choose the right communication channel. This example uses
        // a POST request with JSON as a data structure but your configuration
        // could be different.
        xhr.open( 'POST', 'http://...../uploadc.php', 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', () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const response = xhr.response;
                    if ( response && (response.url || response.urls) ) {
                        resolve( response.url ? { default: response.url } : response.urls );
                    } else if ( response && response.error ) {
                        return reject( response.error.message );
                    } else {
                        resolve( response.url ? { default: response.url } : response.urls );
                    }

                } else {
                    return reject( genericErrorText );
                }
            }


        } );

        // 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 );
    }



    // 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();
        }
    }

}

【问题讨论】:

    标签: javascript php file file-upload ckeditor


    【解决方案1】:

    抱歉,代码没有问题。此问题是由于服务器端数据不干净造成的:

    它只允许注册用户做这个文件上传,这会导致响应中有一些不可见的东西,所以 xmlhttprequest 无法正确处理。

    我使用 ob_end_clean() 来丢弃缓存的数据,它现在可以工作了

    谢谢

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多