How to do CKEditor 5 Image Uploading?

时光总嘲笑我的痴心妄想 提交于 2019-11-30 02:30:20
Ganesh prajapati

Success response :

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

Failure response :

{
    "uploaded": false,
    "error": {
        "message": "could not upload this image"
    }
}

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"
        }';
   }
  }

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

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?.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!