如何进行 CKEditor 5 图片上传?

Posted

技术标签:

【中文标题】如何进行 CKEditor 5 图片上传?【英文标题】:How to do CKEditor 5 Image Uploading? 【发布时间】:2018-08-29 08:39:07 【问题描述】:
ClassicEditor
    .create( editorElement, 
        ckfinder: 
            uploadUrl: 'my_server_url'
        
     )
    .then( ... )
    .catch( ... );

我的服务器响应应该是什么?我在后端使用 Java。 无论我的反应是什么,它都会抛出一个对话框“无法上传文件”。

【问题讨论】:

对于任何偶然发现这个试图锻炼如何使用 srcset 属性并提供多种图像尺寸的人,请参阅此 SO 帖子:***.com/questions/60304900/… 【参考方案1】:

成功响应:


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

失败响应:


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

【讨论】:

谢谢!我不知道为什么我在 CKEditor 文档中找不到这个文档... 谢谢!这在任何地方的文档中都没有解释! CKEditor 考虑到受欢迎程度的记录如此糟糕,真是令人惊讶:( 拯救我的一天你的美丽 【参考方案2】:

这是我的 Ckeditor 5 和 Phalcon 框架的代码。#products_desc 指向 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>

和我的 php 控制器:

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

 
 ?>

【讨论】:

【参考方案3】:
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: `$APIforums`,
        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())
   
/>

【讨论】:

【参考方案4】:

我在 React 中的操作方式应该类似。我有为此的自定义上传器。

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)

使用上面的:

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())
    
  />
)

【讨论】:

【参考方案5】:

ckfinder.uploadUrl 属性配置CKFinderUploadAdapter 插件。该插件负责与CKFinder's server-side connector的通信。

因此,换句话说,您的服务器应该运行 CKFinder 的服务器端连接器。这是一个专有软件,所以我不会深入探讨它的工作原理。

如果您想了解配置图片上传的所有方法,请阅读How to enable image upload support in CKEditor 5?。

【讨论】:

我找到了 CKFinder 的 PHP 和 ASP.NET 服务器端连接器。你能提供 Java Spring 的任何文档吗? 唯一的 CKFinder for Java 是 2.x 版本,它是用纯 Java Servlet 编写的(不支持 Spring Framework)。为了使其与 CKEditor 5 一起使用,您需要使用 uploadUrl。这将允许拖放上传。手册可以在这里找到:docs-old.ckeditor.com/CKFinder_2.x/Developers_Guide/Java。 CKFinder for Java 可以从这里下载 - ckeditor.com/ckeditor-4/download/#ckfinder。【参考方案6】:

可以配置CKEditor上传文件

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( ... );

欲了解更多详情,请访问此链接:https://docs.ckeditor.com/ckeditor5/latest/features/image-upload.html

【讨论】:

以上是关于如何进行 CKEditor 5 图片上传?的主要内容,如果未能解决你的问题,请参考以下文章

CKEditor + CKFinder (上传图片出现问题)

CKEditor 5 注册多个上传适配器

急!急!急!asp.net ckeditor3.5.3如何实现添加图片上传功能!代码越详细越好,最好可以直接运行的!

Django-CKEditor 图片上传

ckeditor 上传图片 php版

ckeditor编辑器如何做复制图片上传(包括本地图片及远程图片),以插件方式实现