Answers:
首先实例化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文档尚不完整,但是,如果您遵循上述内容,它将像冠军一样工作。
我已经发布了一个有关将旧的FCKEditor中可用的FileBrowser集成到CKEditor中的小教程。
http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/
它包含执行此操作的分步说明,非常简单。希望对此有所帮助的人对本教程有所帮助。
我本人只是经历了学习过程。我想通了,但是我同意文档的编写对我来说有点吓人。对我而言,最大的“ aha”时刻是我了解到,对于浏览而言,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 / path和网址中由CKeditor提供的CKEditorFuncNum:
function myOnclickHandler(){
//..
window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, pathToImage);
window.close();
}
同样,上传者只需调用您提供的url,例如upload.php,然后再次提供$ _GET ['CKEditorFuncNum']。目标是iframe,因此,从$ _FILES保存文件后,您将您的反馈传递给CKeditor,如下所示:
$funcNum = $_GET['CKEditorFuncNum'];
exit("<script>window.parent.CKEDITOR.tools.callFunction($funcNum, '$filePath', '$errorMessage');</script>");
下面是一个易于理解的自定义浏览器脚本。尽管它不允许用户在服务器中浏览,但是它允许您在调用浏览器时指示从哪个目录提取图像文件。
都是相当基本的编码,因此它应该可以在所有相对较新的浏览器中使用。
CKeditor只会使用提供的网址打开一个新窗口
/*
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')
});
<?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>
我花了一段时间试图找出答案,这就是我所做的。我已经很简单地分解了它,因为这就是我所需要的。
在您的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
%>
这是我使用的方法。这非常简单,并且效果很好。
在CK编辑器的根目录中,有一个名为config.js的文件。
我添加了这个(您不需要querystring的东西,这仅用于我们的文件管理器)。我还对显示的默认按钮进行了外观设计和更改:
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');
在zerokspot上的一篇名为CKEditor 3.0中的 “ 自定义文件浏览器回调 ”的文章对此进行了处理。最相关的部分引用如下:
因此,选择文件后,在文件浏览器中要做的就是使用正确的回调编号(通常为1)和所选文件的URL调用此代码:
window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);
对于快速上传器,此过程非常相似。最初,我认为编辑器可能正在侦听200 HTTP返回代码,并且可能会查看一些标头字段或类似内容以确定上传文件的位置,但是随后-通过一些Firebug监视-我注意到所有发生的事情上传后为以下代码:
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage);
</script>
如果上传失败,请将设置
errorMessage
为一些非零长度的字符串并清空url,反之则成功。
首先实例化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>';
经过大量的自定义文件上传的研发之后,最终编辑器的文档还不清楚,我终于找到了这种解决方案。它对我有用,我希望对其他人也有帮助。
对于那些想了解Servlet / JSP实现的人,这里是您的实现方法...我还将在下面解释uploadimage。
1)首先,请确保已将filebrowser和uploadimage变量添加到config.js文件中。也让您在plugins文件夹中也具有uploadimage和filebrowser文件夹。
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(您所需要的只是在script标记中)当您单击浏览服务器按钮时,此页面将在迷你窗口中打开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);
}
}
那就是所有人。希望它能帮助某人。