How to do CKEditor 5 Image Uploading?

前端 未结 6 1714
故里飘歌
故里飘歌 2020-12-13 11:12
ClassicEditor
    .create( editorElement, {
        ckfinder: {
            uploadUrl: \'my_server_url\'
        }
    } )
    .then( ... )
    .catch( ... );


        
相关标签:
6条回答
  • 2020-12-13 11:49

    Success response :

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

    Failure response :

    {
        "uploaded": false,
        "error": {
            "message": "could not upload this image"
        }
    }
    
    0 讨论(0)
  • 2020-12-13 12:01

    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"
            }';
       }
      }
    
     }
     ?>
    
    0 讨论(0)
  • 2020-12-13 12:02

    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

    0 讨论(0)
  • 2020-12-13 12:04
    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())
      } }
    />
    
    0 讨论(0)
  • 2020-12-13 12:09

    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())
        }}
      />
    )
    
    0 讨论(0)
  • 2020-12-13 12:13

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

    0 讨论(0)
提交回复
热议问题