CKEDITOR,图片上传(filebrowserUploadUrl)

时间:2010-01-22 05:41:41

标签: ckeditor

我正在使用CKEDITOR,并希望能够允许用户在文本编辑器中上传和嵌入图像......

以下JS是加载CKEDITOR的东西:

CKEDITOR.replace( 'meeting_notes',
    {
        startupFocus : true,
        toolbar :
            [
                ['ajaxsave'],
                ['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
                ['Cut','Copy','Paste','PasteText'],
                ['Undo','Redo','-','RemoveFormat'],
                ['TextColor','BGColor'],
                ['Maximize', 'Image']
            ],
        filebrowserUploadUrl : '/notes/add/ajax/upload-inline-image/index.cfm'
    }
);

我遇到的问题是filebrowserUploadUrl ...那个URL应该返回CKEDITOR以使这个过程起作用?

由于

12 个答案:

答案 0 :(得分:43)

网址应指向您可能拥有的自定义文件浏览器网址。

我已经在我的一个项目中完成了这个,我在我的博客上发布了关于这个主题的教程

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

本教程提供了有关如何在CKEditor中集成FCKEditor的内置FileBrowser的分步说明,如果您不想自己创建。它很简单。

答案 1 :(得分:14)

可能为时已晚。您的代码是正确的,所以请再次检查您的文件在filebrowserUploadUrl

CKEDITOR.replace( 'editor1', {
    filebrowserUploadUrl: "upload/upload.php" 
} );

上传.php文件

if (file_exists("images/" . $_FILES["upload"]["name"]))
{
 echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
 move_uploaded_file($_FILES["upload"]["tmp_name"],
 "images/" . $_FILES["upload"]["name"]);
 echo "Stored in: " . "images/" . $_FILES["upload"]["name"];
}

答案 2 :(得分:5)

新CKeditor没有包含文件管理器(CKFinder是应付的)。 您可以在CKeditor中集成好看且易于实现的免费文件管理器。

http://labs.corefive.com/2009/10/30/an-open-file-manager-for-ckeditor-3-0/

您下载它,将其复制到您的项目中。 所有说明都在那里,但您基本上只是将路径添加到代码中添加的filemanager index.html页面。

CKEDITOR.replace( 'meeting_notes',
{
startupFocus : true,
toolbar :
[
['ajaxsave'],
['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
['Cut','Copy','Paste','PasteText'],
['Undo','Redo','-','RemoveFormat'],
['TextColor','BGColor'],
['Maximize', 'Image']
],
filebrowserUploadUrl : '/filemanager/index.html' // you must write path to filemanager where you have copied it.
});    

支持大多数语言(php,asp,MVC&& aspx - ashx,...))。

答案 3 :(得分:3)

如果您不想购买CKFinder,就像我不想购买CKFinder一样,那么我为CKEditor 4写了一个非常可靠的上传器。它由第二种形式组成,位于textarea表格的正上方,并利用iframe黑客,尽管它的名字,它是无缝和不引人注目的。

图像成功上传后,它将显示在您的CKEditor窗口中,以及已存在的任何内容。

editor.php (表单页面):

<?php
set_time_limit ( 3600 )
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Content Editor</title>
<link href="jquery-ui-1.10.2/themes/vader/ui.dialog.css" rel="stylesheet" media="screen" id="dialog_ui" />
<link href="jquery-ui-1.10.2/themes/vader/jquery-ui.css" rel="stylesheet" media="screen" id="dialog_ui" />
<script src="jquery-ui-1.10.2/jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.2/jquery.form.js"></script>
<script src="jquery-ui-1.10.2/ui/jquery-ui.js"></script>
<script src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/config.js"></script>
<script src="ckeditor/adapters/jquery.js"></script>
<script src="ckeditor/plugin2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#editor').ckeditor({ height: 400, width:600});
});

function placePic(){

    function ImageExist(url){
       var img = new Image();
       img.src = url;
       return img.height != 0;
    }

var filename = document.forms['uploader']['uploadedfile'].value;
document.forms['uploader']['filename'].value = filename;
var url = 'http://www.mydomain.com/external/images/cms/'+filename;
document.getElementById('uploader').submit();
var string = CKEDITOR.instances.editor.getData();
var t = setInterval(function(){

            var exists = ImageExist(url);
            if(exists === true){
                    if(document.getElementById('loader')){
                        document.getElementById('loader').parentNode.removeChild(document.getElementById('loader'));
                    }
                    CKEDITOR.instances.editor.setData(string + "<img src=\""+url+"\" />");
                    clearInterval(t);
            }
            else{
                if(! document.getElementById("loader")){
                    var loader = document.createElement("div");
                    loader.setAttribute("id","loader");
                    loader.setAttribute("style","position:absolute;margin:-300px auto 0px 240px;width:113px;height:63px;text-align:center;z-index:10;");
                    document.getElementById('formBox').appendChild(loader);

                    var loaderGif = document.createElement("img");
                    loaderGif.setAttribute("id","loaderGif");
                    loaderGif.setAttribute("style","width:113px;height:63px;text-align:center;");
                    loaderGif.src = "external/images/cms/2dumbfish.gif";
                    document.getElementById('loader').appendChild(loaderGif);
                }
            }

            },100);
}

function loadContent(){
if(document.forms['editorform']['site'].value !== "" && document.forms['editorform']['page'].value !== ""){
    var site = document.forms['editorform']['site'].value;
    var page = document.forms['editorform']['page'].value;
    var url = site+"/"+page+".html";
    $.ajax({
        type: "GET",
        url: url,
        dataType: 'html',
        success: function (html) {
            CKEDITOR.instances.editor.setData(html);
        }
    });
}
}
</script>
<style>
button{
  width: 93px;
  height: 28px;
  border:none;
  padding: 0 4px 8px 0;
  font-weight:bold
}
#formBox{
    width:50%;
margin:10px auto 0px auto;
font-family:Tahoma, Geneva, sans-serif;
font-size:12px;
}
#field{
position:absolute;
top:10px;
margin-left:300px;
margin-bottom:20px;
}
#target{
position:absolute;
top:100px;
left:100px;
width:400px;
height:100px;
display:none;
}
.textField{
    padding-left: 1px;
border-style: solid;
border-color: black;
border-width: 1px;
font-family: helvetica, arial, sans serif;
padding-left: 1px;
}
#report{
float:left;
margin-left:20px;
margin-top:10px;
font-family: helvetica, arial, sans serif;
font-size:12px;
color:#900;
}
</style>
</head>

<body>
<?php
if(isset($_GET['r'])){ ?><div id="report">
<?php echo $_GET['r']; ?> is changed.
</div><?php
}
?>
<div id="formBox">
<form id="uploader" name="uploader" action="editaction.php"  method="post" target="target" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<input type="hidden" name="filename" value="" />
Insert image:&nbsp;<input name="uploadedfile" type="file" class="textField" onchange="placePic();return false;" />&nbsp;&nbsp;
</form>

<form name="editorform" id="editorform" method="post" action="editaction.php" >
<div id="field" >Site:&nbsp;<select name="site"  class="textField" onchange="loadContent();return false;">
    <option value=""></option>
    <option value="scubatortuga">scubatortuga</option>
    <option value="drytortugascharters">drytortugascharters</option>
    <option value="keyscombo">keyscombo</option>
    <option value="keywesttreasurehunters">keywesttreasurehunters</option>
    <option value="spearfishkeywest">spearfishkeywest</option>
</select>
Page:&nbsp;<select name="page" class="textField" onchange="loadContent();return false;">
    <option value=""></option>
    <option value="one">1</option>
    <option value="two">2</option>
    <option value="three">3</option>
    <option value="four">4</option>
</select>
</div><br />
<textarea name="editor" id="editor"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<iframe name="target" id="target"></iframe>
</body>
</html>

以下是操作页面 editaction.php ,它会执行实际的文件上传:

<?php
//editaction.php

foreach($_POST as $k => $v){
    ${"$k"} = $v;
}
//fileuploader.php
if($_FILES){
  $target_path = "external/images/cms/";
  $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
  if(! file_exists("$target_path$filename")){
    move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
  }
}
else{
    $string = stripslashes($editor);
    $filename = "$site/$page.html";
    $handle = fopen($filename,"w");
    fwrite($handle,$string,strlen($string));
    fclose($handle);
    header("location: editor.php?r=$filename");
}
?>

答案 4 :(得分:2)

我的最新一期是如何在CKEditor中集成CKFinder进行图片上传。这是解决方案。

  1. 下载CKEditor并在您的网络文件夹根目录中提取。

  2. 下载CKFinder并使用ckeditor文件夹解压缩。

  3. 然后添加对CKEditor,CKFinder和put

    的引用
     <CKEditor:CKEditorControl ID="CKEditorControl1" runat="server"></CKEditor:CKEditorControl>
    

    到你的aspx页面。

  4. 在代码隐藏页面OnLoad事件中添加此代码段

    protected override void OnLoad(EventArgs e)
    {
      CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
      _FileBrowser.BasePath = "ckeditor/ckfinder/";
      _FileBrowser.SetupCKEditor(CKEditorControl1);
    }
    
  5. 编辑Confic.ascx文件。

    public override bool CheckAuthentication()
    {
      return true;
    }
    
    // Perform additional checks for image files.
    SecureImageUploads = true;
    
  6. source

答案 5 :(得分:2)

对于CKeditor版本4,编辑器希望从服务器端返回JSON。较旧的版本可能需要text / html类型的响应,并带有一个javascript代码段。有关此Explanation of return formats的说明,请参见此链接。在服务器端,如果使用的是C#,则可以创建如下数据模型:

Pagina.aspx

并使用以下命令从您的上传例程返回结果:

namespace editors.Models
{
    public class PostModel
    {
        public string CKEditor { get; set; }  // for older editors
        public string CKEditorFuncNum { get; set; }  // for older editors
        public string langCode { get; set; }  // for older editors
        public int uploaded { get; set; } 
        public string filename { get; set; }
    }
}

尽管.net最有可能自动将其制成json,但请确保您返回的是内容类型application / json。

作为那些想要检查上传的文件是否真的是图像文件的人的注释;如果您使用的是Asp.net核心,则需要以非标准方式安装system.drawing库。 Here's how to do that

还请注意,您可以将config.js文件中的发布类型更改为 config.filebrowserUploadMethod ='form'; ,而不是 config.filebrowserUploadMethod ='xhr';;

答案 6 :(得分:1)

对于那些在Grails ckeditor插件中有相同问题的人来说

filebrowserUploadUrl:&#39; / YourAppName / CK / OFM&#39;

调用处理图像uploade的函数。如果你想使用自己的自定义函数,你可以给出该文件路径。

答案 7 :(得分:1)

这个简单的演示可以帮助您获得所需的内容。  这是您要从中上传图像的html / php代码:

<html>
<head>
 <script src="http://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
  </head>
<body>
<form  action="index.php" method="POST"  style="width:500xp;">

<textarea rows="5" name="content" id="content"></textarea>

<br>
<input type="submit" name="submit" value="Post">

</form>
<script>
 CKEDITOR.replace( 'content', {
  height: 300,
  filebrowserUploadUrl: "upload.php"
 });
</script>
</body>
</html>

,这是upload.php文件的代码。

 <?php
if(isset($_FILES['upload']['name']))
{
 $file = $_FILES['upload']['tmp_name'];
 $file_name = $_FILES['upload']['name'];
 $file_name_array = explode(".", $file_name);
 $extension = end($file_name_array);
 //we want to save the image with timestamp and randomnumber
 $new_image_name = time() . rand(). '.' . $extension;
 chmod('upload', 0777);
 $allowed_extension = array("jpg", "gif", "png");
 if(in_array($extension, $allowed_extension))
 {
  move_uploaded_file($file, 'upload/' . $new_image_name);
  $function_number = $_GET['CKEditorFuncNum'];
  $url = 'upload/' . $new_image_name;
  $message = '';
  echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($function_number, '$url', '$message');</script>";
 }
}
?>

注意:不要忘记在同一文件夹中创建一个文件夹“ upload”,并将所有三个文件都保留在同一目录中。稍后,您可以在了解其工作原理后更改其目录。同样不要忘记按如下图所示将其发送到服务器。

screenshot

答案 8 :(得分:0)

该URL将指向您自己的服务器端文件上载操作。文档没有详细说明,但幸运的是, Don Jones 填补了一些空白:

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

另见:

http://zerokspot.com/weblog/2009/09/09/custom-filebrowser-callbacks-ckeditor/

答案 9 :(得分:0)

我最近也需要回答这个问题,我花了几个小时来弄清楚,所以我决定用一些更新的信息和完整的答案来复活这个问题。 / p>

最终我偶然发现this tutorial对我说得很清楚。对于stackoverflow,我将在这里重申教程以防它被删除。我还将在教程中添加一些更改,使其成为更灵活的解决方案。

入门

让我们从ckeditor的任何版本开始,(基本的,标准的,完整的,自定义的)唯一的要求是你有插件imagefilebrowser

(在撰写本文时,所有包都包含这两个插件,除了基本插件,但它可以添加到基本插件中)

上传必要的ckeditor文件后,请确保您的安装正常。

确保链接ckeditor.js文件脚本<script src="ckeditor/ckeditor.js"></script>,然后将其初始化为:

$(document).ready(function() {
    CKEDITOR.replace( 'editor1' );
});
<textarea name="editor1"></textarea>

CKEditor配置

现在我们必须告诉CKEditor我们要启用上传。您可以通过进入ckeditor文件夹并编辑`config.js&#39;来完成此操作。我们需要添加这一行:

在主要功能E.G

内的某处

config.filebrowserUploadUrl = '/uploader/upload.php';

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';

    config.filebrowserUploadUrl = '/uploader/upload.php';
};
  

注意:此URL来自您的项目根目录。无论您从何处加载此文件,它都将从您的站点索引开始。这意味着,如果您的网址是example.com,则此网址会显示http://example.com/uploader/upload.php

在此之后,CKEditor配置完成!那很简单呃?

事实上,如果你现在再次测试你的图片上传,你会得到一个上传选项,虽然它还没有完成工作。

enter image description here

服务器配置

现在,您将在此之前的步骤中注意到它以upload.php文件结尾。这是困扰我的部分,我想有一些默认可以用这个,但据我所知,没有。幸运的是,我发现了一个可行的,我对它进行了一些更改以允许更多的自定义。

因此,让我们转到您在上一步中提供的路径,为了本教程的连续性,我将使用/uploader/upload.php

在此位置,创建一个名为(您猜对了)的文件upload.php

此文件将处理我们的文件上传。

我会放入自定义上传课程,但它基于我发现并分叉的this github

  

upload.php的:

<?php
// Upload script for CKEditor.
// Use at your own risk, no warranty provided. Be careful about who is able to access this file
// The upload folder shouldn't be able to upload any kind of script, just in case.
// If you're not sure, hire a professional that takes care of adjusting the server configuration as well as this script for you.
// (I am not such professional)

// Configuration Options: Change these to alter the way files being written works
$overwriteFiles = false;

//THESE SETTINGS ONLY MATTER IF $overwriteFiles is FALSE

    //Seperator between the name of the file and the generated ending.
    $keepFilesSeperator = "-"; 

    //Use "number" or "random". "number" adds a number, "random" adds a randomly generated string.
    $keepFilesAddonType = "random"; 

    //Only usable when $keepFilesAddonType is "number", this specifies where the number starts iterating from.
    $keepFilesNumberStart = 1; 

    //Only usable when $keepFilesAddonType is "random", this specifies the length of the string.
    $keepFilesRandomLength = 4; 

//END FILE OVERWRITE FALSE SETTINGS

// Step 1: change the true for whatever condition you use in your environment to verify that the user
// is logged in and is allowed to use the script
if (true) {
    echo("You're not allowed to upload files");
    die(0);
}

// Step 2: Put here the full absolute path of the folder where you want to save the files:
// You must set the proper permissions on that folder (I think that it's 644, but don't trust me on this one)
// ALWAYS put the final slash (/)
$basePath = "/home/user/public_html/example/pages/projects/uploader/files/";

// Step 3: Put here the Url that should be used for the upload folder (it the URL to access the folder that you have set in $basePath
// you can use a relative url "/images/", or a path including the host "http://example.com/images/"
// ALWAYS put the final slash (/)
$baseUrl = "http://example.com/pages/projects/uploader/files/";

// Done. Now test it!



// No need to modify anything below this line
//----------------------------------------------------

// ------------------------
// Input parameters: optional means that you can ignore it, and required means that you
// must use it to provide the data back to CKEditor.
// ------------------------

// Optional: instance name (might be used to adjust the server folders for example)
$CKEditor = $_GET['CKEditor'] ;

// Required: Function number as indicated by CKEditor.
$funcNum = $_GET['CKEditorFuncNum'] ;

// Optional: To provide localized messages
$langCode = $_GET['langCode'] ;

// ------------------------
// Data processing
// ------------------------

// The returned url of the uploaded file
$url = '' ;

// Optional message to show to the user (file renamed, invalid file, not authenticated...)
$message = '';

// in CKEditor the file is sent as 'upload'
if (isset($_FILES['upload'])) {
    // Be careful about all the data that it's sent!!!
    // Check that the user is authenticated, that the file isn't too big,
    // that it matches the kind of allowed resources...
    $name = $_FILES['upload']['name'];

    //If overwriteFiles is true, files will be overwritten automatically.
    if(!$overwriteFiles) 
    {
        $ext = ".".pathinfo($name, PATHINFO_EXTENSION);
        // Check if file exists, if it does loop through numbers until it doesn't.
        // reassign name at the end, if it does exist.
        if(file_exists($basePath.$name)) 
        {
            if($keepFilesAddonType == "number") {
                $operator = $keepFilesNumberStart;
            } else if($keepFilesAddonType == "random") {
                $operator = bin2hex(openssl_random_pseudo_bytes($keepFilesRandomLength/2));
            }
            //loop until file does not exist, every loop changes the operator to a different value.
            while(file_exists($basePath.$name.$keepFilesSeperator.$operator)) 
            {
                if($keepFilesAddonType == "number") {
                    $operator++;
                } else if($keepFilesAddonType == "random") {
                    $operator = bin2hex(openssl_random_pseudo_bytes($keepFilesRandomLength/2));
                }
            }
            $name = rtrim($name, $ext).$keepFilesSeperator.$operator.$ext;
        }
    }
    move_uploaded_file($_FILES["upload"]["tmp_name"], $basePath . $name);

    // Build the url that should be used for this file   
    $url = $baseUrl . $name ;

    // Usually you don't need any message when everything is OK.
//    $message = 'new file uploaded';   
}
else
{
    $message = 'No file has been sent';
}
// ------------------------
// Write output
// ------------------------
// We are in an iframe, so we must talk to the object in window.parent
echo "<script type='text/javascript'> window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message')</script>";

?>
  

我对此类所做的更改允许您启用/禁用文件覆盖,并为您提供一些选项,以便您何时不想覆盖文件。原始类总是覆盖,没有选项。

默认情况下,此类设置为保留所有文件,而不会覆盖。您可以使用这些设置来更好地满足您的需求。

如果您注意到,有一段代码只是一个if(true)语句,显然总是如此

if (true) {
    echo("You're not allowed to upload files");
    die(0);
}

这是为了安全。您应该在此处检查用户上载是否已登录/允许上载。如果您不担心,可以删除这些代码行或将其设置为if(false) (不推荐)

您还需要编辑$basePath$baseUrl变量以满足您的服务器需求,否则它将无效。除非你想玩游戏,否则下面的所有内容都可以保留。

  

此类不提供文件保护,您可能希望使用它来使其更安全,因此人们无法将脚本或病毒上传到您的服务器。

我希望这个小小的教程可以帮助某些人,因为我在为自己努力工作的过程中工作了太长时间,我希望我可以节省一些时间。

我在上面链接的教程中还有一些简洁的故障排除步骤,可以帮助您找到出现问题的原因。

enter image description here

答案 10 :(得分:0)

您可以使用此代码

     <script>
                // Replace the <textarea id="editor"> with a CKEditor
                // instance, using default configuration.

                CKEDITOR.config.filebrowserImageBrowseUrl = '/admin/laravel-filemanager?type=Files';
                CKEDITOR.config.filebrowserImageUploadUrl = '/admin/laravel-filemanager/upload?type=Images&_token=';
                CKEDITOR.config.filebrowserBrowseUrl = '/admin/laravel-filemanager?type=Files';
                CKEDITOR.config.filebrowserUploadUrl = '/admin/laravel-filemanager/upload?type=Files&_token=';

                CKEDITOR.replaceAll( 'editor');
   </script>

答案 11 :(得分:-5)

要从您的桌面或任何地方上传图像简单拖放,您可以通过复制图像并使用ctrl + v将其粘贴到文本区域来实现此目的