Ckeditor and ckfinder 配置实现截图上传图片到远程服务器

来源:互联网 发布:fanuc铣孔螺旋下刀编程 编辑:程序博客网 时间:2024/05/01 02:55

Ckeditorand ckfinder 配置实现上传图片到远程服务器

1.      从ck官网下载两个文件。


(文件夹解压后不必要的文件可以删除,samples、help 等以及skin皮肤文件夹下不要的皮肤也可以删掉,还有lang语言包下面除了zh-cn和en外其他也可以删掉,有你也看不懂)

2.      创建一个文件夹(比如:pasteDemo),将ckeditor和ckfinder放入其中。

3.      ckeditor/config.js用于配置ckeditor,比如config.language = ‘zh-cn’; config.skin= 'v2';

分别是配置语言和皮肤。

4.      在页面中加载ckeditor编辑器。见pasteDemo.php (已实现直接截图,粘贴至编辑器,谷歌浏览器支持,火狐已自带此功能)

<html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK"><title></title><link rel="stylesheet" href="css/std.css" type="text/css"><script type="text/javascript" src="ckfinder/ckfinder.js"></script><script type="text/javascript" src="ckeditor/ckeditor.js"></script></head><body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"  ><form name=postcontent method="POST" action="upload.php"><table width="100%" border="0" cellspacing="0" cellpadding="0">      <tr>         <td class="bigred" align="center" background="images/bgloveyou2.gif" height="10"></td>      </tr>      <tr>        <td class="bigred" bgcolor="f7f7f7" align="center">内容</td>      </tr>      <tr>         <td align="center"  height='530'> <div id='divHtml' style="height:100%;display:;">   <textarea rows="80" cols="50" name="Editor"></textarea>  <script language="javascript">CKEDITOR.replace( 'Editor',{ //图片上传发送路径,returnURL为参数,到服务器后跳转回来的页面filebrowserImageUploadUrl : 'http://10.0.6.200/uploadimg.php?returnURL=http://localhost/pasteDemo/jump.php'});//当ckeditor加载完成后绑定事件,这里绑定的是粘贴事件,实现截图直接粘贴图片在编辑器中CKEDITOR.instances["Editor"].on("instanceReady", function () {  this.document.on("paste", Paste);   }); function Paste(e){var items = e.data.$.clipboardData.items;for (var i = 0; i < items.length; ++i) {var item = e.data.$.clipboardData.items[i];if (items[i].kind == 'file' && items[i].type == 'image/png') {//FileReader可以参考<p>APIvar fileReader = new FileReader();//readAsDataURL是一个异步过程,这里提供回调方法fileReader.onloadend = function () {var d = this.result.substr( this.result.indexOf(',')+1);//往ckeditor中插入图片,base64编码过的CKEDITOR.instances.Editor.insertHtml("<img src='data:image/jpeg;base64,"+d+"'>"); };fileReader.readAsDataURL(item.getAsFile());break; }  }}</script></div>        </td>      </tr>      <tr>         <td>           <table align="center" >            <tr>               <td >                 <input type="submit" value="完 成" name="submit" class="btnOrange"/>              </td>              <td >                 <input type="reset"value="重 置" name="reset" class="btnBlack" />              </td>                         </tr>          </table>          <hr noshade color=ff9933>        </td>      </tr>     </table> </form></body></html>


5.      提交编辑器内容到本地的upload.php

<?$Editor = $_POST['Editor']; $Editor = stripslashes(eregi_replace("\n","",$Editor));preg_match_all('/\"data.*?\"/',$Editor,$pic);//获取字符串data以及data以后的图片信息//提交过来的内容中包含截图if($pic[0]){$pics = array();$strlen = 0;//截取的字符串长度foreach($pic[0] as $key => $val){$strlen=strpos($val,'base64,')+7;//加上“base64,”的长度$temp[$key]=substr($val,$strlen,-1);}$pics['base64File'] = $temp;//将图片POST到服务器$url = "http://10.0.6.200/uploadimg.php";//这里是接收图片的服务器的url$curl = curl_init();curl_setopt($curl,CURLOPT_URL,$url);curl_setopt($curl,CURLOPT_POST,true);curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($pics));curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);$response=curl_exec($curl);if ($response === FALSE) { echo "cURL Error: " . curl_error($curl);}curl_close($curl);//返回服务器上图片的url$result = json_decode($response,true);foreach($pic[0] as $key => $val){$Editor = str_replace($val, $result[$key], $Editor);}}echo $Editor;//直接打印出编辑器中的内容,因为图片的url已经替换为远程,所以图片将直接显示出来//随机生成文件名称,方法来自网络function mySetFileName() {$gettime = explode(' ', microtime());$string = 'abcdefghijklmnopgrstuvwxyz0123456789';$rand = '';for ($x = 0; $x < 3; $x++) {$rand .= substr($string, mt_rand(0, strlen($string) - 1), 1);}return date("ymdHis") . substr($gettime[0], 2, 6) . $rand;}?>  


6.      服务器的接收文件uploadimg.php

<?phpob_start(); if($_FILES){//上传图片文件$uploadfile = $_FILES; $returnURL = $_GET['returnURL'];$filepath='D:\zengq\DedeAMPZ\WebRoot\Default\upload\images/';//服务器上保存图片的路径$filename=mySetFileName().strstr($uploadfile['upload']['name'],".");//随机生成的名字加上上传图片的格式后缀if (false === move_uploaded_file($uploadfile['upload']['tmp_name'], $filepath.$filename)) {die("上传文件失败");}ob_end_clean();header('Location:'.$returnURL.'?fileName='.$filename);//跳转到传过来的returnURL参数,并传递参数文件名称exit();}else{//截图上传图片$imgsrc=array();foreach ($_POST['base64File'] as $key => $val ) {$imgsrc[$key]=getPic(base64_decode($val));}ob_end_clean();exit(json_encode($imgsrc));//返回图片远程路径数组}//将图片写入服务器文件中,并返回地址function getPic($pic64){   $filename ="upload/images/".mySetFileName().'.png';   if($pic64){      fopen($filename,'w+');   }// 首先我们要确定文件存在并且可写。if (is_writable($filename)) {    if (!$handle = fopen($filename, 'a')) {         print "不能打开文件 $filename";         exit;    }    //将图片写入到我们打开的文件中。    if (!fwrite($handle, $pic64)) {        print "不能写入到文件 $filename";        exit;    }    print "成功地将 图片 写入到文件";    fclose($handle);$imgurl = "http://10.0.6.200/".$filename;return $imgurl;} else { return false;} }//生成图片名称function mySetFileName() {$gettime = explode(' ', microtime());$string = 'abcdefghijklmnopgrstuvwxyz0123456789';$rand = '';for ($x = 0; $x < 3; $x++) {$rand .= substr($string, mt_rand(0, strlen($string) - 1), 1);}return date("ymdHis") . substr($gettime[0], 2, 6) . $rand;}


7.      上传成功后跳转到本地文件jump.php,在pasteDemo.php的filebrowserImageUploadUrl中配置的,returnURL

 

<?php if(!$_GET['msg']&&$_GET['fileName']){////本地跳转到图像页面//图片的远程路径src$url = "http://10.0.6.200/upload/images/".$_GET['fileName'];//以下为查看ckfinder中的源码找到的,上传成功后会跳转到图像的那一块然后显示出图片的预览效果,并且源文件一栏已经填入图片的远程urlheader('Content-Type: text/html; charset=utf-8');echo "<script type=\"text/javascript\">";  echo "window.parent.CKEDITOR.tools.callFunction(2, '" . str_replace("'", "\\'",$url) . "', '" .str_replace("'", "\\'", ''). "');";echo "</script>";}else{//输出报错信息die("<script language=\"javascript\">alert(\" ".$_GET['msg']." \");history.go(-1)</script>");exit;}?>

 

至此已完成配置:

本地项目文件pasteDemo文件夹下:


保存图片的服务器文件: