How can you integrate a custom file browser/uploader with CKEditor?
Solution 1:
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.
Solution 2:
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.
Solution 3:
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>
Solution 4:
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
%>