ckeditor 5 实现图片上传接口

关于图片上传的官方参考文档:

https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html

按照官方文档的说法,有三种方法能实现图片上传的功能:

  1. 使用官方的云服务;
  2. 使用ckfinger插件(收费);
  3. 自定义图片上传适配器并实现上传接口。

撇开前两种,这里说第三种。

先说ckeditor图片上传的原理:

在编辑器点击上传图片后,在编辑器内插入图片占位符,定义的适配器会调用图片上传接口,接口上传图片后需要返回特定格式json数据,编辑器从json数据取数据,替换图片占位符为真正的图片资源。

首先自定义适配器,官方有提供,拿来用就好,下面的代码根据提示更改,并且保证已正确引用。

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.
        // 下面的API换成自己的接口地址
        xhr.open( 'POST', 'API', 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 );
    };
}

// #editor是表单id

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

        // ...
    } )
    .catch( error => {
        console.log( error );
    } );

API接口实现代码,适配器调用的就是这个接口。

<?php

header('Content-Type:application/json');

class upload {
    public function upload_file(){
        $urls=[];
        $counts=count($_FILES);
        foreach ($_FILES as $item){
            move_uploaded_file($item['tmp_name'],$item['name']);
            // $url是返回上传图片后的资源地址
            $url=$this->'图片上传路径'.$item['name'];
            array_push($urls,$url);
        }



        $arr=["uploaded"=>$counts,"url"=>$urls];


        return json_encode($arr);


    }

}

$res=new upload($site_url);

print_r($res->upload_file());

接口会返回json数据,格式如下:

{
    uploaded: counts,
    url: {'img_url',
          'img_url',
             ...   }
}

基本没什么问题了。

Bearye

Coder, designer, photographer...

发表留言

人生在世,错别字在所难免,无需纠正。