[ACCEPTED]-How can you integrate a custom file browser/uploader with CKEditor?-ckeditor

Accepted answer
Score: 177

Start by registering your custom browser/uploader 26 when you instantiate CKEditor. You can designate 25 different URLs for an image browser vs. a 24 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

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

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

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

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

CKEditor's "upload" tab 12 will submit a file in the field "upload" - in 11 PHP, that goes to $_FILES['upload']. What 10 CKEditor wants your server to output is 9 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 8 to give it that callback parameter, the 7 URL of the file, and optionally a message. If 6 the message is an empty string, nothing 5 will display; if the message is an error, then 4 url should be an empty string.

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

Score: 14

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


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

Score: 11

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

I call the browser and the uploader 19 with

CKEDITOR.replace( 'body',  
    filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +  
    filebrowserUploadUrl: 'upload.php?type=Files&dir=' +  

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

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

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

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

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

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

CKeditor merely opens 1 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

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>  
    <title>browse file</title>  
    <meta charset="utf-8">  

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





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

    $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="">',   

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

// 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";  



// make a js array from the php array
images = [  

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,  

        if( tgt.nodeName != 'IMG' )  

        url = '<?php echo $dir;?>' + '/' + tgt.title;  

        this.onclick = null;  

        window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, url);  

Score: 9

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

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

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

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

    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
                File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
            End If
    End if

    imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
    Response.write imgop
Score: 8

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

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

I added this (you don't 4 need the querystring stuff, this is just 3 for our file manager). I also included some 2 skinning and changing of the default buttons 1 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:

Score: 7

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

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


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

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

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

Score: 4

Start by registering your custom browser/uploader 8 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

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


$upload_dir = array(
 'img'=> '/phpwork/test/uploads/editor-images/',
 'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'

$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

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

Score: 4

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

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

2) This part 16 is where it tripped me up:

The Ckeditor website 15 documentation says you need to use these 14 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 );

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

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

editor.jsp (all you need is this 9 in your script tag) This page will open 8 filebrowser.jsp in a mini window when you 7 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 6 the custom file browser you built which 5 will contain the methods mentioned above)

<script src="../../ckeditor/ckeditor.js"></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 );

//when this window opens it will load all the images which you send from the FileBrowser Servlet. 
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

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

4) UploadImage Servlet

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

config.uploadUrl = '/UploadImage';

Then you can 2 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);

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

More Related questions