【问题标题】:How can you integrate a custom file browser/uploader with CKEditor?如何将自定义文件浏览器/上传与 CKEditor 集成?
【发布时间】:2010-12-02 16:30:11
【问题描述】:

官方文档不太清楚 - 将自定义文件浏览器/上传器与 CKEditor 集成的正确方法是什么? (v3 - 不是 FCKEditor)

【问题讨论】:

    标签: ckeditor


    【解决方案1】:

    在您实例化 CKEditor 时,首先注册您的自定义浏览器/上传器。您可以为图像浏览器和普通文件浏览器指定不同的 URL。

    <script type="text/javascript">
    CKEDITOR.replace('content', {
        filebrowserBrowseUrl : '/browser/browse/type/all',
        filebrowserUploadUrl : '/browser/upload/type/all',
        filebrowserImageBrowseUrl : '/browser/browse/type/image',
    filebrowserImageUploadUrl : '/browser/upload/type/image',
        filebrowserWindowWidth  : 800,
        filebrowserWindowHeight : 500
    });
    </script>
    

    您的自定义代码将收到一个名为 CKEditorFuncNum 的 GET 参数。保存它 - 这是你的回调函数。假设您将其放入$callback

    当有人选择一个文件时,运行这个 JavaScript 来通知 CKEditor 选择了哪个文件:

    window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)
    

    其中“url”是他们选择的文件的 URL。可选的第三个参数可以是您希望在标准警报对话框中显示的文本,例如“非法文件”或其他内容。如果第三个参数是错误消息,则将 url 设置为空字符串。

    CKEditor 的“上传”选项卡将在“上传”字段中提交一个文件 - 在 PHP 中,该文件转到 $_FILES['upload']。 CKEditor 希望你的服务器输出的是一个完整的 JavaScript 块:

    $output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
    echo $output;
    

    同样,您需要向它提供回调参数、文件的 URL 以及可选的消息。如果消息是空字符串,则不会显示任何内容;如果消息是错误的,那么 url 应该是一个空字符串。

    CKEditor 的官方文档在所有这些方面都不完整,但如果您按照上述操作,它将像冠军一样工作。

    【讨论】:

    • 我不敢相信这个过程的开发人员文档如此稀少。感谢您填写详细信息。
    • 这是很棒的信息!比官方文档好。
    • 非常感谢!但它是 CKEditorFunNum,而不是 Name =P
    • @emzero,我想可能是CKEditorFuncName,也许CKEditor现在使用CKEditorFuncNum的越多。无论如何,答案是正确的!
    • 另外,如果您需要隐藏“上传选项卡”以便只允许上传图片,您可以使用:CKEDITOR.on('dialogDefinition', function(ev) { // 使用对话框事件中的名称及其定义 // data.var dialogName = ev.data.name; var dialogDefinition = ev.data.definition; // 检查定义是否来自我们感兴趣的对话框 // 感兴趣(链接和图片 dialog). if ( dialogName == 'link' || dialogName == 'image' ) { // 移除上传标签 dialogDefinition.removeContents( 'Upload' ); } });
    【解决方案2】:

    我已经发布了一个关于将旧 FCKEditor 中可用的 FileBrowser 集成到 CKEditor 的小教程。

    http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/

    它包含执行此操作的分步说明,而且非常简单。我希望任何寻找这个的人都会觉得这个教程很有帮助。

    【讨论】:

      【解决方案3】:

      我自己刚刚经历了学习过程。我想通了,但我同意文档的编写方式对我来说有点吓人。对我来说最大的“啊哈”时刻是理解浏览,CKeditor 所做的只是打开一个新窗口并在 url 中提供一些参数。它允许您添加其他参数,但建议您需要在值上使用 encodeURIComponent()。

      我用

      调用浏览器和上传器
      CKEDITOR.replace( 'body',  
      {  
          filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +  
              encodeURIComponent('content/images'),  
          filebrowserUploadUrl: 'upload.php?type=Files&dir=' +  
              encodeURIComponent('content/images')  
      }
      

      对于浏览器,在打开的窗口 (browse.php) 中,您使用 php 和 js 提供选项列表,然后在您提供的 onclick 处理程序上,您调用带有两个参数的 CKeditor 函数,所选图像的 url/路径和 CKeditor 在 url 中提供的 CKEditorFuncNum:

      function myOnclickHandler(){  
      //..    
          window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, pathToImage);  
          window.close();
      }       
      

      同样,uploader 只需调用您提供的 url,例如 upload.php,然后再次提供 $_GET['CKEditorFuncNum']。目标是 一个 iframe,因此,在您从 $_FILES 保存文件后,您将反馈传递给 CKeditor,如下所示:

      $funcNum = $_GET['CKEditorFuncNum'];  
      exit("<script>window.parent.CKEDITOR.tools.callFunction($funcNum, '$filePath', '$errorMessage');</script>");  
      

      下面是一个简单易懂的自定义浏览器脚本。虽然它不允许用户在服务器中四处导航,但它允许您在调用浏览器时指示从哪个目录中提取图像文件。

      这都是相当基本的编码,因此它应该适用于所有相对现代的浏览器。

      CKeditor 只是打开一个带有提供的 url 的新窗口

      /*          
          in CKeditor **use encodeURIComponent()** to add dir param to the filebrowserBrowseUrl property
      
          Replace content/images with directory where your images are housed.
      */          
              CKEDITOR.replace( 'editor1', {  
                  filebrowserBrowseUrl: '**browse.php**?type=Images&dir=' + encodeURIComponent('content/images'),  
                  filebrowserUploadUrl: 'upload.php?type=Files&dir=' + encodeURIComponent('content/images') 
              });   
      

      // ========= 下面为 browse.php 的完整代码

      <?php  
      header("Content-Type: text/html; charset=utf-8\n");  
      header("Cache-Control: no-cache, must-revalidate\n");  
      header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");  
      
      // e-z params  
      $dim = 150;         /* image displays proportionally within this square dimension ) */  
      $cols = 4;          /* thumbnails per row */
      $thumIndicator = '_th'; /* e.g., *image123_th.jpg*) -> if not using thumbNails then use empty string */  
      ?>  
      <!DOCTYPE html>  
      <html>  
      <head>  
          <title>browse file</title>  
          <meta charset="utf-8">  
      
          <style>  
              html,  
              body {padding:0; margin:0; background:black; }  
              table {width:100%; border-spacing:15px; }  
              td {text-align:center; padding:5px; background:#181818; }  
              img {border:5px solid #303030; padding:0; verticle-align: middle;}  
              img:hover { border-color:blue; cursor:pointer; }  
          </style>  
      
      </head>  
      
      
      <body>  
      
      <table>  
      
      <?php  
      
      $dir = $_GET['dir'];    
      
      $dir = rtrim($dir, '/'); // the script will add the ending slash when appropriate  
      
      $files = scandir($dir);  
      
      $images = array();  
      
      foreach($files as $file){  
          // filter for thumbNail image files (use an empty string for $thumIndicator if not using thumbnails )
          if( !preg_match('/'. $thumIndicator .'\.(jpg|jpeg|png|gif)$/i', $file) )  
              continue;  
      
          $thumbSrc = $dir . '/' . $file;  
          $fileBaseName = str_replace('_th.','.',$file);  
      
          $image_info = getimagesize($thumbSrc);  
          $_w = $image_info[0];  
          $_h = $image_info[1]; 
      
          if( $_w > $_h ) {       // $a is the longer side and $b is the shorter side
              $a = $_w;  
              $b = $_h;  
          } else {  
              $a = $_h;  
              $b = $_w;  
          }     
      
          $pct = $b / $a;     // the shorter sides relationship to the longer side
      
          if( $a > $dim )   
              $a = $dim;      // limit the longer side to the dimension specified
      
          $b = (int)($a * $pct);  // calculate the shorter side
      
          $width =    $_w > $_h ? $a : $b;  
          $height =   $_w > $_h ? $b : $a;  
      
          // produce an image tag
          $str = sprintf('<img src="%s" width="%d" height="%d" title="%s" alt="">',   
              $thumbSrc,  
              $width,  
              $height,  
              $fileBaseName  
          );  
      
          // save image tags in an array
          $images[] = str_replace("'", "\\'", $str); // an unescaped apostrophe would break js  
      
      }
      
      $numRows = floor( count($images) / $cols );  
      
      // if there are any images left over then add another row
      if( count($images) % $cols != 0 )  
          $numRows++;  
      
      
      // produce the correct number of table rows with empty cells
      for($i=0; $i<$numRows; $i++)   
          echo "\t<tr>" . implode('', array_fill(0, $cols, '<td></td>')) . "</tr>\n\n";  
      
      ?>  
      </table>  
      
      
      <script>  
      
      // make a js array from the php array
      images = [  
      <?php   
      
      foreach( $images as $v)  
          echo sprintf("\t'%s',\n", $v);  
      
      ?>];  
      
      tbl = document.getElementsByTagName('table')[0];  
      
      td = tbl.getElementsByTagName('td');  
      
      // fill the empty table cells with data
      for(var i=0; i < images.length; i++)  
          td[i].innerHTML = images[i];  
      
      
      // event handler to place clicked image into CKeditor
      tbl.onclick =   
      
          function(e) {  
      
              var tgt = e.target || event.srcElement,  
                  url;  
      
              if( tgt.nodeName != 'IMG' )  
                  return;  
      
              url = '<?php echo $dir;?>' + '/' + tgt.title;  
      
              this.onclick = null;  
      
              window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, url);  
      
              window.close();  
          }  
      </script>  
      </body>  
      </html>            
      

      【讨论】:

        【解决方案4】:

        我花了一段时间试图弄清楚这一点,这就是我所做的。我把它分解得很简单,因为这是我需要的。

        直接在你的ckeditor文本区域下方,像这样输入上传文件>>>>

        <form action="welcomeeditupload.asp" method="post" name="deletechecked">
            <div align="center">
                <br />
                <br />
                <label></label>
                <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
                <script type="text/javascript">
                //<![CDATA[
                    CKEDITOR.replace( 'editor1',
                    {
                        filebrowserUploadUrl : 'updateimagedone.asp'
                    });
                //]]>
                </script>
                <br />
                <br />
                <br />
                <input type="submit" value="Update">
            </div>
        </form>
        

        '然后添加你的上传文件,这是我用 ASP 编写的。如果您使用的是 PHP 等,只需将 ASP 替换为您的上传脚本,但请确保页面输出相同的内容。

        <%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
        <%
            if Request("CKEditorFuncNum")=1 then
                Set Upload = Server.CreateObject("Persits.Upload")
                Upload.OverwriteFiles = False
                Upload.SetMaxSize 5000000, True
                Upload.CodePage = 65001
        
                On Error Resume Next
                Upload.Save "d:\hosting\belaullach\senate\legislation"
        
                Dim picture
                For Each File in Upload.Files
                    Ext = UCase(Right(File.Path, 3))
                    If Ext <> "JPG" Then
                            If Ext <> "BMP" Then
                            Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
                            Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
                            End if
                    Else
                        File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
                        f1=File.fileName
                    End If
                Next
            End if
        
            fnm="/senate/legislation/"&f1
            imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
            'imgop="callFunction('1','"&fnm&"',"");"
            Response.write imgop
        %>
        

        【讨论】:

          【解决方案5】:

          这是我使用的方法。这很简单,而且效果很好。

          在CK编辑器根目录下有一个名为config.js的文件

          我添加了这个(你不需要查询字符串的东西,这只是为了我们的文件管理器)。我还对显示的默认按钮进行了一些换肤和更改:

          CKEDITOR.editorConfig = function(config) {
          
              config.skin = 'v2';
              config.startupFocus = false;
              config.filebrowserBrowseUrl = '/admin/content/filemanager.aspx?path=Userfiles/File&editor=FCK';
              config.filebrowserImageBrowseUrl = '/admin/content/filemanager.aspx?type=Image&path=Userfiles/Image&editor=FCK';
              config.toolbar_Full =
              [
                  ['Source', '-', 'Preview', '-'],
                  ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker'], //, 'Scayt' 
                  ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
                  '/',
                  ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'],
                  ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
                  ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
                  ['Link', 'Unlink', 'Anchor'],
                  ['Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar'],
                  '/',
                  ['Styles', 'Format', 'Templates'],
                  ['Maximize', 'ShowBlocks']
              ];
          
          };
          

          然后,我们的文件管理器调用:

          opener.SetUrl('somefilename');
          

          【讨论】:

            【解决方案6】:

            zerokspot 上一篇题为Custom filebrowser callbacks in CKEditor 3.0 的文章处理了这个问题。下面引用了最相关的部分:

            所以你必须从文件中做的所有事情 选择文件时的浏览器 是用权利调用这个代码 回拨号码(通常为 1)和 所选文件的网址:

            window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);
            

            对于快速上传者,流程是 很相似。一开始我以为 编辑可能正在听 200 HTTP 返回码,也许看起来 进入一些标题字段或其他东西 像这样确定的位置 上传的文件,但是然后 - 通过 一些 Firebug 监控 - 我注意到 上传后发生的一切 是以下代码:

            &lt;script type="text/javascript"&gt;
            window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage); &lt;/script&gt;

            如果上传失败,设置 errorMessage 到一些非零长度 字符串并清空网址,反之亦然 成功则反之。

            【讨论】:

            • 你可以给出网址 -> zerokspot.com/weblog/2009/09/09/…
            • 感谢您找到我的博客,clops,您至少可以链接回它或根本链接到它,而不是复制/粘贴我的博客文章。
            • @Jon & @Horst:感谢您指出这一点。如果我删掉了任何需要放回的相关内容,请告诉我。
            【解决方案7】:

            在您实例化 CKEditor 时,首先注册您的自定义浏览器/上传器。

            <script type="text/javascript">
            CKEDITOR.replace('content', {
                filebrowserUploadUrl: "Upload File Url",//http://localhost/phpwork/test/ckFileUpload.php
                filebrowserWindowWidth  : 800,
                filebrowserWindowHeight : 500
            });
            </script>
            

            上传文件代码(ckFileUpload.php) & 将上传文件放在项目的根目录。

            // HERE SET THE PATH TO THE FOLDERS FOR IMAGES AND AUDIO ON YOUR SERVER (RELATIVE TO THE ROOT OF YOUR WEBSITE ON SERVER)
            
            $upload_dir = array(
             'img'=> '/phpwork/test/uploads/editor-images/',
             'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'
            );
            
            // HERE PERMISSIONS FOR IMAGE
            $imgset = array(
             'maxsize' => 2000,     // maximum file size, in KiloBytes (2 MB)
             'maxwidth' => 900,     // maximum allowed width, in pixels
             'maxheight' => 800,    // maximum allowed height, in pixels
             'minwidth' => 10,      // minimum allowed width, in pixels
             'minheight' => 10,     // minimum allowed height, in pixels
             'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'),  // allowed extensions
            );
            
            // HERE PERMISSIONS FOR AUDIO
            $audioset = array(
             'maxsize' => 20000,    // maximum file size, in KiloBytes (20 MB)
             'type' => array('mp3', 'ogg', 'wav'),  // allowed extensions
            );
            
            // If 1 and filename exists, RENAME file, adding "_NR" to the end of filename (name_1.ext, name_2.ext, ..)
            // If 0, will OVERWRITE the existing file
            define('RENAME_F', 1);
            
            $re = '';
            if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
              define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name'])));  //get filename without extension
            
              // get protocol and host name to send the absolute image path to CKEditor
              $protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
              $site = $protocol. $_SERVER['SERVER_NAME'] .'/';
              $sepext = explode('.', strtolower($_FILES['upload']['name']));
              $type = end($sepext);    // gets extension
              $upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
              $upload_dir = trim($upload_dir, '/') .'/';
            
              //checkings for image or audio
              if(in_array($type, $imgset['type'])){
                list($width, $height) = getimagesize($_FILES['upload']['tmp_name']);  // image width and height
                if(isset($width) && isset($height)) {
                  if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
                  if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
                  if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
                }
              }
              else if(in_array($type, $audioset['type'])){
                if($_FILES['upload']['size'] > $audioset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $audioset['maxsize']. ' KB.';
              }
              else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';
            
              //set filename; if file exists, and RENAME_F is 1, set "img_name_I"
              // $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
              function setFName($p, $fn, $ex, $i){
                if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
                else return $fn .$ex;
              }
            
              $f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
              $uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name;  // full file path
            
              // If no errors, upload the image, else, output the errors
              if($re == '') {
                if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
                  $CKEditorFuncNum = $_GET['CKEditorFuncNum'];
                  $url = $site. $upload_dir . $f_name;
                  $msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
                  $re = in_array($type, $imgset['type']) ? "window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')"  //for img
                   : 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent();  dialog.hide();';
                }
                else $re = 'alert("Unable to upload the file")';
              }
              else $re = 'alert("'. $re .'")';
            }
            
            @header('Content-type: text/html; charset=utf-8');
            echo '<script>'. $re .';</script>';
            

            在为自定义文件上传进行了大量研发后,Ck-editor 文档不清楚,最后我找到了这个解决方案。它对我有用,我希望它对其他人也有帮助。

            【讨论】:

              【解决方案8】:

              对于想了解 Servlet/JSP 实现的人来说,这里是你如何去做的……我也会在下面解释 uploadimage。

              1) 首先确保您已将 filebrowseruploadimage 变量添加到您的 config.js 文件。让您在插件文件夹中也有 uploadimagefilebrowser 文件夹。

              2) 这部分是让我绊倒的地方:

              Ckeditor 网站文档说你需要使用这两种方法:

              function getUrlParam( paramName ) {
                  var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
                  var match = window.location.search.match( reParam );
                  return ( match && match.length > 1 ) ? match[1] : null;
              }
              function returnFileUrl() {
                  var funcNum = getUrlParam( 'CKEditorFuncNum' );
                  var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
                  window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
                  window.close();
              }
              

              他们没有提到的是这些方法必须在 不同的页面,而不是您从中单击浏览服务器按钮的页面。

              因此,如果您在页面 editor.jsp 中初始化了 ckeditor,那么您需要在页面 filebrowser.jsp 中创建一个文件浏览器(带有基本的 html/css/javascript) .

              editor.jsp(你只需要在你的脚本标签中)当你点击浏览服务器按钮时,这个页面将在一个迷你窗口中打开filebrowser.jsp。

              CKEDITOR.replace( 'editor', {
                  filebrowserBrowseUrl: '../filebrowser.jsp', //jsp page with jquery to call servlet and get image files to view
                  filebrowserUploadUrl: '../UploadImage', //servlet
              
              });
              

              filebrowser.jsp(是您构建的自定义文件浏览器,将包含上述方法)

              <head>
              <script src="../../ckeditor/ckeditor.js"></script>
              </head>
              <body>
              <script>
              
              
              function getUrlParam( paramName ) {
                  var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
                  var match = window.location.search.match( reParam );
                  return ( match && match.length > 1 ) ? match[1] : null;
              }
              
              function returnFileUrl() {
                  var funcNum = getUrlParam( 'CKEditorFuncNum' );
              var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
                  window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
                  window.close();
              }
              
              
              //when this window opens it will load all the images which you send from the FileBrowser Servlet. 
              getImages();
              function getImages(){
                  $.get("../FileBrowser", function(responseJson) {    
                      //do something with responseJson (like create <img> tags and update the src attributes) 
                  });
              }
              
                 //you call this function and pass 'fileUrl' when user clicks on an image that you loaded into this window from a servlet
              returnFileUrl();
              </script>
              </body>
              

              3) FileBrowser Servlet

              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  Images i = new Images();
                  List<ImageObject> images = i.getImages(); //get images from your database or some cloud service or whatever (easier if they are in a url ready format)
                  String json = new Gson().toJson(images);
                  response.setContentType("application/json");
                  response.setCharacterEncoding("UTF-8");
                  response.getWriter().write(json);
              }
              

              4) UploadImage Servlet

              返回 ckeditor 的 config.js 文件并添加以下行:

              //https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
              config.uploadUrl = '/UploadImage';
              

              然后你也可以拖放文件:

                 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              
              
                              Images i = new Images();
              
                 //do whatever you usually do to upload your image to your server (in my case i uploaded to google cloud storage and saved the url in a database. 
              
                 //Now this part is important. You need to return the response in json format. And it has to look like this:
              
              //      https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
              //      response must be in this format:
              //      {
              //          "uploaded": 1,
              //          "fileName": "example.png",
              //          "url": "https://www.cats.com/example.png"
              //      }
              
                                  String image = "https://www.cats.com/example.png";
                                      ImageObject objResponse = i.getCkEditorObjectResponse(image);
                                      String json = new Gson().toJson(objResponse);
                                      response.setContentType("application/json");
                                      response.setCharacterEncoding("UTF-8");
                                      response.getWriter().write(json);
                                  }
                              }
              

              这就是所有人。希望它可以帮助某人。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-12-07
                • 2012-07-14
                • 1970-01-01
                • 2012-02-09
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多