LoginSignup
16
15

More than 5 years have passed since last update.

CKEditor 5の画像アップロードを実装する

Posted at

CKEditorとは

リッチなエディターを簡単に作ってくれるライブラリです。
非エンジニア向けの管理画面を作るときに重宝します。

image.png
https://ckeditor.com/ckeditor-5/

画像アップロードを簡単にやってくれるサービスもあるんですが、

image.png
https://ckeditor.com/ckeditor-cloud-services/

高いのであまり使いたくない・・・

ので、自分で画像アップロードAPIを作る方法を紹介します。

クライアント側の設定

ckfinderuploadUrlにアップロード先を指定する

ClassicEditor
    .create( editorElement, {
        ckfinder: {
            uploadUrl: '/path/to/image/upload'
        }
    } )
    .then( ... )
    .catch( ... );

APIのレスポンス

ドキュメントのどこにも載ってない(ような気がした)ので、ソースコードを読んで返すべきレスポンスを特定します。

        xhr.addEventListener( 'load', () => {
            const response = xhr.response;


            if ( !response || !response.uploaded ) {
                return reject( response && response.error && response.error.message ? response.error.message : genericError );
            }


            resolve( {
                default: response.url
            } );

レスポンスはどうやらこんな感じで返せばよさそう

成功時のレスポンス

{
  "url": "http://example.com/path/to/image",
  "uploaded": true
}

失敗時のレスポンス

{
  "uploaded": false,
  "error": {
    "message": "Error message here"
  }
}
16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15