How can you integrate a custom file browser/uploader with CKEditor?

前端 未结 8 1520
南方客
南方客 2020-11-28 00:14

The official documentation is less than clear - what\'s the correct way to integrate a custom file browser/uploader with CKEditor? (v3 - not FCKEditor)

相关标签:
8条回答
  • 2020-11-28 00:49

    Start by registering your custom browser/uploader when you instantiate CKEditor.

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

    Code for upload file(ckFileUpload.php) & put the upload file on root dir of your project.

    // 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 documentation is not clear after doing alot of R&D for custom file upload finally i have found this solution. It work for me and i hope it will helpful to others as well.

    0 讨论(0)
  • 2020-11-28 00:50

    I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.

    Directly below your ckeditor text area, enter the upload file like this >>>>

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

    'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.

    <%@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
    %>
    
    0 讨论(0)
  • 2020-11-28 00:55

    This is the approach I've used. It's quite straightforward, and works just fine.

    In the CK editor root directory there is a file named config.js

    I added this (you don't need the querystring stuff, this is just for our file manager). I also included some skinning and changing of the default buttons shown:

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

    Then, our file manager calls this:

    opener.SetUrl('somefilename');
    
    0 讨论(0)
  • 2020-11-28 00:56

    Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.

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

    Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback.

    When someone selects a file, run this JavaScript to inform CKEditor which file was selected:

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

    Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.

    CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:

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

    Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.

    The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.

    0 讨论(0)
  • 2020-11-28 00:57

    For people wondering about a Servlet/JSP implementation here's how you go about doing it... I will be explaining uploadimage below also.

    1) First make sure you have added the filebrowser and uploadimage variable to your config.js file. Make you also have the uploadimage and filebrowser folder inside the plugins folder too.

    2) This part is where it tripped me up:

    The Ckeditor website documentation says you need to use these two methods:

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

    What they don't mention is that these methods have to be on a different page and not the page where you are clicking the browse server button from.

    So if you have ckeditor initialized in page editor.jsp then you need to create a file browser (with basic html/css/javascript) in page filebrowser.jsp.

    editor.jsp (all you need is this in your script tag) This page will open filebrowser.jsp in a mini window when you click on the browse server button.

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

    filebrowser.jsp (is the custom file browser you built which will contain the methods mentioned above)

    <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) The 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

    Go back to your config.js file for ckeditor and add the following line:

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

    Then you can drag and drop files also:

       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);
                        }
                    }
    

    And that's all folks. Hope it helps someone.

    0 讨论(0)
  • 2020-11-28 01:01

    An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:

    So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

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

    For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

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

    If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

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