Loading...

Tích hợp upload file Laravel với CKEditor 5


CKEditor 5 ra với nhiều editor đơn gản và đẹp như:

  • Classic editor
  • Inline editor
  • Balloon editor
  • Decoupled editor

Hiện tại Laravel Wordpress CMS của mình của tích hợp vào CKEditor 5 bản DecoupledEditor.

Trong bài viết này chia sẽ thêm upload image lên editor save lại database của mình.


# Javascript

# khi submit save gán lại vào textarea

$(document).on('submit', '.submit', function () {
    let html = $(".ckeditor5").html();
    $(".text-ckeditor5").val(html)
})


# Script load CkEditor
DecoupledEditor
    .create(document.querySelector('.ckeditor5'), {
        extraPlugins: [ MyCustomUploadAdapterPlugin ],
    })
    .then(editor => {
        const toolbarContainer = document.querySelector('#toolbar-container');
        toolbarContainer.appendChild(editor.ui.view.toolbar.element);

        let content = $('.ckeditor5').closest('.box-ckeditor5').children('.text-ckeditor5').val();
        editor.setData(content);
    })
    .catch(error => {

    });

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

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

    // 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', configs.link_media_upload , 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', () => {
            const response = xhr.response;

            // This example assumes the XHR server's "response" object will come with
            // an "error" which has its own "message" that can be passed to reject()
            // in the upload promise.
            //
            // Your integration may handle upload errors in a different way so make sure
            // it is done properly. The reject() function must be called when the upload fails.
            if ( !response || response.error ) {
                return reject( response && response.error ? response.error.message : genericErrorText );
            }

            // If the upload is successful, resolve the upload promise with an object containing
            // at least the "default" URL, pointing to the image on the server.
            // This URL will be used to display the image in the content. Learn more in the
            // UploadAdapter#upload documentation.
            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 => {
                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 );
    }
}

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


Note: configs.link_media_upload là link upload. Ex: https://app.test/admin/media/upload?_token=m7kbnO6cTsOTRBskjS92zqqf8sTNernWx9gedmo3


PHP


/**
 * upload content for ckeditor
 *
 * @param  Request  $request
 * @return array
 */
public function upload(Request $request)
{
    $type = $request->get('type');
    $url = '';
    if ($request->file('upload')) {
        $objectFile = $request->file('upload');

        $upload = $this->mediaService->upload($objectFile);
        if (1 == $upload['status']) {
            $url = asset('storage'.$upload['content']['file_name']);

            $msg = 'Image uploaded successfully';
        } else {
            $msg = trans('common.upload.error');
        }
    } else {
        $msg = trans('error_file_invalid');
    }

        return [
            'status' => !empty($url) ? 1 : 0,
            'name' => $upload['content']['name'] ?? '',
            'file_name' => $upload['content']['file_name'] ?? '',
            'file_id' => $upload['content']['id'] ?? 0,
            'url' => $url,
            'message' => $msg,
        ];
}



# Bài viết cùng chuyên mục