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

前端 未结 8 1518
南方客
南方客 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 01:04

    I just went through the learning process myself. I figured it out, but I agree the documentation is written in a way that was sorta intimidating to me. The big "aha" moment for me was understanding that for browsing, all CKeditor does is open a new window and provide a few parameters in the url. It allows you to add additional parameters but be advised you will need to use encodeURIComponent() on your values.

    I call the browser and the uploader with

    CKEDITOR.replace( 'body',  
    {  
        filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +  
            encodeURIComponent('content/images'),  
        filebrowserUploadUrl: 'upload.php?type=Files&dir=' +  
            encodeURIComponent('content/images')  
    }
    

    For the browser, in the open window (browse.php) you use php & js to supply a list of choices and then upon your supplied onclick handler, you call a CKeditor function with two arguments, the url/path to the selected image and CKEditorFuncNum supplied by CKeditor in the url:

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

    Simarly, the uploader simply calls the url you supply, e.g., upload.php, and again supplies $_GET['CKEditorFuncNum']. The target is an iframe so, after you save the file from $_FILES you pass your feedback to CKeditor as thus:

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

    Below is a simple to understand custom browser script. While it does not allow users to navigate around in the server, it does allow you to indicate which directory to pull image files from when calling the browser.

    It's all rather basic coding so it should work in all relatively modern browsers.

    CKeditor merely opens a new window with the url provided

    /*          
        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') 
            });   
    

    // ========= complete code below for 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>            
    
    0 讨论(0)
  • 2020-11-28 01:11

    I have posted one small tutorial about integrating the FileBrowser available in old FCKEditor into CKEditor.

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

    It contains step by step instructions for doing so and its pretty simple. I hope anybody in search of this will find this tutorial helpful.

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