How to do CKEditor 5 Image Uploading?
Asked Answered
C

6

13
ClassicEditor
    .create( editorElement, {
        ckfinder: {
            uploadUrl: 'my_server_url'
        }
    } )
    .then( ... )
    .catch( ... );

What should be my server response? I am using Java in the backend. Whatever my response is, it throws a dialog box 'cannot upload file'.

Caddie answered 20/3, 2018 at 13:39 Comment(1)
For anyone who's stumbled across this trying to workout how to use the srcset attribute and supply multiple image sizes, please see this SO post: #60305400Tideway
E
33

Success response :

{
    "uploaded": true,
    "url": "http://127.0.0.1/uploaded-image.jpeg"
}

Failure response :

{
    "uploaded": false,
    "error": {
        "message": "could not upload this image"
    }
}
Elbaelbart answered 14/4, 2018 at 15:49 Comment(3)
Thanks! I don't know why I couldn't find this documented in the CKEditor documentation...Cardiograph
Thank you! This isn't explained in their documentation anywhere! It is such a surprise at how poorly documented CKEditor is considering the popularity :(Tideway
Save my day you beauty <3Cardigan
D
2
class UploadAdapter {
  constructor( loader ) {
    this.loader = loader;
    this.upload = this.upload.bind(this)
    this.abort = this.abort.bind(this)
  }

  upload() {
    const data = new FormData();
    data.append('typeOption', 'upload_image');
    data.append('file', this.loader.file);

    return axios({
        url: `${API}forums`,
        method: 'post',
        data,
        headers: {
          'Authorization': tokenCopyPaste()
        },
        withCredentials: true
      }).then(res => {
        console.log(res)
        var resData = res.data;
        resData.default = resData.url;
        return resData;
      }).catch(error => {
        console.log(error)
        return Promise.reject(error)
      });
  }

  abort() {
    // Reject promise returned from upload() method.
  }
}               
<CKEditor
  editor={ ClassicEditor }
  data="<p>Hello from CKEditor 5!</p>"
  config={{}}
  onInit={ editor => {
    editor.ui.view.editable.element.style.height = '200px';
    editor.plugins.get( 'FileRepository' ).createUploadAdapter = function( loader ) {
      return new UploadAdapter( loader );
    };
  } }
  onChange={ ( event, editor ) => {
    console.log(editor.getData())
  } }
/>
Drag answered 19/10, 2018 at 21:43 Comment(0)
O
2

this is my code for Ckeditor 5 and Phalcon framework.#products_desc point to textarea id.

<script>

var myEditor;

ClassicEditor
.create( document.querySelector( '#products_desc' ) ,
{
    ckfinder: {
        uploadUrl: 'Ckfinder/upload'
    }
}
)
.then( editor => {
    console.log( 'Editor was initialized', editor );
    myEditor = editor;
} )
.catch( err => {
    console.error( err.stack );
} );</script>

and my php controller:

 <?php
 use Phalcon\Mvc\Controller;

 class CkfinderController extends Controller
 {

    public function uploadAction()
  {

   try {
    if ($this->request->hasFiles() == true) {
        $errors = []; // Store all foreseen and unforseen errors here
        $fileExtensions = ['jpeg','jpg','png','gif','svg'];
        $uploadDirectory = "../public/Uploads/";
        $Y=date("Y");
        $M=date("m");
           foreach ($this->request->getUploadedFiles() as $file) {
        if (in_array($file->getExtension(),$fileExtensions)) {
           if($file->getSize()<2000000) 
           {

            if (!file_exists($uploadDirectory.$Y)) {
                mkdir($uploadDirectory.$Y, 0777, true);
            }
            if (!file_exists($uploadDirectory.$Y.'/'.$M)) {
                mkdir($uploadDirectory.$Y.'/'.$M, 0777, true);
            }
            $namenew=md5($file->getName().time()).'.'.$file->getExtension();
            $uploadDirectory .=$Y.'/'.$M.'/'; 
            $file->moveTo($uploadDirectory.$namenew);
           }
           else{
            $errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
           }
        }
        else{$errors[] = "This file extension is not allowed. Please upload a JPEG ,svg,gif,,jpg,PNG file";}

    if(empty($errors))
    {   
       echo '{
        "uploaded": true,
        "url": "http://localhost/cms/public/Uploads/'.$Y.'/'.$M.'/'.$namenew.'"}';
    }
    else{
        echo '{
        "uploaded": false,
        "error": {
            "message": "could not upload this image1"
        }';}
    }
}
else{
    echo '{
    "uploaded": false,
    "error": {
        "message": "could not upload this image1"
    }';}
}
catch (\Exception $e) {
       echo '{
        "uploaded": false,
        "error": {
            "message": "could not upload this image0"
        }';
   }
  }

 }
 ?>
Odd answered 30/10, 2018 at 8:19 Comment(0)
J
2

How I do it in React, should be similar. I have custom uploader for this.

UploadAdapter.js

// Custom Upload Adapter
export class UploadAdapter {
  constructor(loader) {
    this.loader = loader
  }

  async upload() {
    return this.loader.file.then((file) => {
      const data = new FormData()
      data.append("file", file)
      const genericError = `Couldn't upload file: ${file.name}.`

      return axios({
        data,
        method: "POST",
        url: "API_UPLOAD_URL",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
          loader.uploadTotal = progressEvent.total
          loader.uploaded = progressEvent.loaded
          const uploadPercentage = parseInt(
            Math.round((progressEvent.loaded / progressEvent.total) * 100)
          )
        },
      })
        .then(({ data }) => ({ default: data.url }))
        .catch(({ error }) => Promise.reject(error?.message ?? genericError))
    })
  }

  abort() {
    return Promise.reject()
  }
}

// CKEditor FileRepository
export function uploadAdapterPlugin(editor) {
  editor.plugins.get("FileRepository").createUploadAdapter = (loader) =>
    new UploadAdapter(loader)
}

Using the above:

const CustomEditor = () => (
  <CKEditor
    editor={ClassicEditor}
    data="<p>Hello from CKEditor 5!</p>"
    config={{}}
    onInit={(editor) => {
      editor.ui.view.editable.element.style.height = "200px"
      uploadAdapterPlugin(editor)
    }}
    onChange={(event, editor) => {
      console.log(editor.getData())
    }}
  />
)
Jotun answered 18/7, 2020 at 7:8 Comment(0)
M
1

The ckfinder.uploadUrl property configures the CKFinderUploadAdapter plugin. This plugin is responsible for communication with the CKFinder's server-side connector.

So, in other words, your server should run the CKFinder's server-side connector. This is a proprietary software, so I won't go deeper into how it works.

If you wish to learn about all ways to configure image upload, please read How to enable image upload support in CKEditor 5?.

Minimum answered 20/3, 2018 at 13:55 Comment(2)
I found CKFinder's server-side connector for PHP and ASP.NET. Can you provide any documentation for Java Spring?Caddie
The only CKFinder for Java is in version 2.x and it has been written in pure Java Servlets (there is no support for Spring Framework). In order to make it work with CKEditor 5, you need to use uploadUrl. This will allow drag & drop uploads. Manual can be found here: docs-old.ckeditor.com/CKFinder_2.x/Developers_Guide/Java. CKFinder for Java can be downloaded from here - ckeditor.com/ckeditor-4/download/#ckfinder.Hali
A
0

You can configure CKEditor to upload files

ClassicEditor.create( document.querySelector( '#editor' ), {

    cloudServices: {

        tokenUrl: 'https://example.com/cs-token-endpoint',

        uploadUrl: 'https://your-organization-id.cke-cs.com/easyimage/upload/'

    }

} )

.then( ... )

.catch( ... );

For the more details visit this link : https://docs.ckeditor.com/ckeditor5/latest/features/image-upload.html

Adna answered 29/7, 2018 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.