這個範例是跟據之前的ExtJS-CKEditor上傳檔案及圖片使用jsp的方法改寫的,裡面可能有需多jsp的概念存在,不過在php上傳時是沒有問題的,不同於jsp範例,此處直require_once設定檔進來,而不使用讀取外部設定檔的方式。在使用上要修改CKConfig三個上傳參數,指定正確的url路徑。
filebrowserUploadUrl : 'CKEditorUpload.php?Type=File', filebrowserImageUploadUrl : 'CKEditorUpload.php?Type=Image', filebrowserFlashUploadUrl : 'CKEditorUpload.php?Type=Flash',
詳細的說明請參考[ExtJS]WYSIWYG所視即所得網頁編輯器外掛 with CKEditor
有修改過的原始碼如下:
example.js
/*! * Ext JS Library 3.0.0 * Copyright(c) 2006-2009 Ext JS, LLC * [email protected] * http://www.extjs.com/license */ Ext.onReady(function(){ //Ext.QuickTips.init(); // turn on validation errors beside the field globally //Ext.form.Field.prototype.msgTarget = 'side'; var bd = Ext.getBody(); var Form = new Ext.FormPanel({ id: 'Myorm', frame: true, labelAlign: 'top', title: 'CKEditor in ExtJS', bodyStyle:'padding:5px', url:"getHtml.php", width: 750, layout: 'form', // Specifies that the items will now be arranged in columns items: [{ //columnWidth: 1, xtype: 'fieldset', labelWidth: 90, title:'CKEditor', defaults: {width: 700, border:false}, // Default config options for child items defaultType: 'textfield', autoHeight: true, bodyStyle: Ext.isIE ? 'padding:0 0 5px 15px;' : 'padding:10px 15px;', border: false, style: { "margin-left": "10px", // when you add custom margin in IE 6... "margin-right": Ext.isIE6 ? (Ext.isStrict ? "-10px" : "-13px") : "0" // you have to adjust for it somewhere else }, items: [{ xtype: 'ckeditor', fieldLabel: 'Editor', name: 'htmlcode', id:'htmlcode', CKConfig: { /* Enter your CKEditor config paramaters here or define a custom CKEditor config file. */ customConfig : 'config.js', // This allows you to define the path to a custom CKEditor config file. //toolbar: 'Full', toolbar:[['Source'/*,'-','Save','NewPage','Preview','-','Templates'*/], ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], /*['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],*/ ['BidiLtr', 'BidiRtl'],['Link','Unlink','Anchor'], '/', ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'], '/', ['Styles','Format','Font','FontSize'], ['TextColor','BGColor'], ['Maximize', 'ShowBlocks','-'/*,'About'*/] ], skin : 'office2003', //filebrowserUploadUrl : 'ckeditor/uploader?Type=File', //filebrowserImageUploadUrl : 'ckeditor/uploader?Type=Image', //filebrowserFlashUploadUrl : 'ckeditor/uploader?Type=Flash', filebrowserUploadUrl : 'CKEditorUpload.php?Type=File', filebrowserImageUploadUrl : 'CKEditorUpload.php?Type=Image', filebrowserFlashUploadUrl : 'CKEditorUpload.php?Type=Flash', height : 200//, //width: 700 } }] }],buttons:[{ text:'Save', name:'Save', handler:function() { alert(123); Form.getForm().submit(); }//.createDelegate(Form.getForm()) }], renderTo: bd }); });
CKEditorUpload.php
<?php require_once "config.php"; // 目錄及文件的命名格式 $dirFormatter = date("Ym"); $fileFormatter = date("YmdHis"); //echo $baseDir; if (!isset($baseDir) || $baseDir === null ) $baseDir = "UserFiles/"; $realBaseDir = $baseDir; //echo '222'.$realBaseDir.'222'; if (!file_exists($realBaseDir)) { mkdir($realBaseDir,0700); } /** * 取得檔案檔名 */ function getNameWithoutExtension($fileName) { return strtolower(substr($filename,0,strrpos($filename,'.'))); } /** * 取得檔案副檔名 */ function getExtension($fileName) { $data = explode(".",$fileName); //echo 'tee'.strtolower($data[count($data)-1]).'ttt'; if(count($data)>=0) { return strtolower($data[count($data)-1]); } else return ""; } /** * 判斷是否為可上傳檔案 */ function extIsAllowed($fileType, $ext) { $ext = strtolower($ext); $allowList= $allowedExtensions[$fileType]; $denyList =$deniedExtensions[$fileType]; if (strlen($allowList) === 0) { if(strpos($denyList,"|".$ext."|")===false) return true; else return false; } if (strlen($denyList) === 0 ) { if(strpos($allowList,"|".$ext."|")===false) return false; else return true; } return false; }?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>File Upload</title> </head> <body> <?php $typeStr = $_GET["Type"]; if ($typeStr == null) { $typeStr = "File"; } // 要上傳的目錄 $currentPath = $baseDir.$typeStr."/"; //echo $currentPath; if (!file_exists($currentPath)) { mkdir($currentPath,0700); } $currentPath = $currentPath.$dirFormatter."/"; // Web的實際位置 //$currentDirPath = realpath(currentPath); // 判斷檔案是否存在,不存在時則建立 //$dirTest = file($currentDirPath); //echo $currentPath; if (!file_exists($currentPath)) { mkdir($currentPath,0700); } // 檔案上傳後的目錄位置http://xxx.xxx.xx/123/ //$http_url = substr($_SERVER['SCRIPT_NAME'],,$_SERVER['SCRIPT_NAME']); $currentDirPath = realpath(".")."\\".$currentPath; $currentPath = curPageName().$currentPath; //echo $currentDirPath; //echo '<br/>'.$currentPath; //logger.info(currentDirPath); $newName = ""; $fileUrl = ""; $ErrorMsg = ""; if ($enabled) { try { // 取得文件名稱做處理 $fileNameLong = $_FILES['upload']['name']; $fileNameLong = str_replace('\\', '/',$fileNameLong); $pathParts = explode("/",$fileNameLong); $fileName = $pathParts[count($pathParts) - 1]; // 取得副檔名 $ext = getExtension($fileName); //echo $fileName; //echo count($pathParts); //var_dump($pathParts); // 實際要存檔的名稱 $fileName = $fileFormatter.".".$ext; // 上傳檔案的檔名 $nameWithoutExt = getNameWithoutExtension($fileName); $pathToSave = $currentDirPath.$fileName; //echo $pathToSave; $fileUrl = $currentPath.$fileName; //echo $fileUrl; //echo $ext; if (extIsAllowed($typeStr, $ext)) { $counter = 1; while (file_exists($pathToSave)) { $newName = $nameWithoutExt."_".$counter."." .$ext; $fileUrl=$currentPath .$newName; $pathToSave = $currentDirPath.$newName; $counter++; } move_uploaded_file($_FILES['upload']['tmp_name'], $pathToSave); } else { $ErrorMsg = "無效的檔案類型 "; } } catch (Exception $ex) { $ErrorMsg = "無法得知的錯誤!"; } } else { $ErrorMsg = "未啟用CKEditor上傳功能!!"; } // CKEditorFuncNum是要回傳位置 $callback = $_GET["CKEditorFuncNum"]; echo "<script type=\"text/javascript\">"; if ($ErrorMsg ==="") { echo "window.parent.CKEDITOR.tools.callFunction(" .$callback. ",'" . $fileUrl . "',''" . ");"; } else { echo "alert('" . $ErrorMsg . "');"; echo "history.back();"; } echo ("</script>"); //out.flush(); //out.close(); //logger.debug("--- END DOPOST ---"); ?> </body> </html>
config.php
<?php function get_document_root() { if(isset($_SERVER['DOCUMENT_ROOT'])) { return $_SERVER['DOCUMENT_ROOT']; } else { $script = $_SERVER['PHP_SELF']; $full_path = $_SERVER['ORIG_PATH_TRANSLATED']; $fp_parts = split('\\\\',$full_path); $full_path = implod('/',$fp_parts); $script_start = strpost($full_path,$script); return substr($full_path,0,$script_start); } } function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["SCRIPT_NAME"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["SCRIPT_NAME"]; } return $pageURL; } function curPageName() { $data = curPageURL(); $arr = explode("/",$data); $data = ""; for($i=0;$i<count($arr)-1;$i++) { $data = $data.$arr[$i]."/"; } return $data; } $baseDir="userUpload/";// CKEditor上傳檔案存放的目錄 $debug = false;// 是否debug模式 $enabled = true; $allowedExtensions = array("file"=>"","image"=>"|jpg|gif|jpeg|png|bmp","flashs"=>"|wf|fla|");//可上傳的副檔名 $deniedExtensions =array("file"=>"|html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|ftl|", "image"=>"","flash"=>"");;//不可上傳的副檔名 $dirFormatter;// 目錄格式yyyMM $fileFormatter;// 文件格式yyyyMMddHHmmssSSS ?>