nicEdit Internet Explorer Upload

nicEdit 확인간 Internet Explorer 10이하에서 HTML5가 제대로 지원되지 않아
이미지가 업로드 되지 않는 현상을 해결하기 위해 작업 한 결과를 업데이트 해봅니다.

FCK와 같은 다른 WYSIWYG Editor와 달리 아주 가벼운 에디터라 이번에 작업 한번 해봤습니다..

// Edit By Colorweb : 2012-11-01 부분을 참조하면 됩니다.

우선 업로드 파일을 처리하는 nicUpload.php

[crayon lang=”php” toolbar=”false”]
/* NicEdit – Micro Inline WYSIWYG

* Copyright 2007-2009 Brian Kirchoff
*
* NicEdit is distributed under the terms of the MIT license
* For more information visit http://nicedit.com/
* Do not remove this copyright message
*
* nicUpload Reciever Script PHP Edition
* @description: Save images uploaded for a users computer to a directory, and
* return the URL of the image to the client for use in nicEdit
* @author: Brian Kirchoff <briankircho@gmail.com>* @sponsored by: DotConcepts (http://www.dotconcepts.net)
* @version: 0.9.0
*/

// Set the path (relative or absolute) to the directory to save image files
define(’NICUPLOAD_PATH’, ’’);

// Set the URL (relative or absolute) to the directory defined above
define(’NICUPLOAD_URI’, ’’);

$nicupload_allowed_extensions = array(’jpg’,’jpeg’,’png’,’gif’,’bmp’);

// You should not need to modify below this line
$rfc1867 = function_exists(’apc_fetch’) && ini_get(’apc.rfc1867’);

if(!function_exists(’json_encode’)) {
die(‘{”error” : ”Image upload host does not have the required dependicies (json_encode/decode)”}’);
}

$id = $_POST[’APC_UPLOAD_PROGRESS’];

// Edit By Colorweb : 2012-11-01
if(empty($id)) {
$d = $_GET[’d’];
}
// Edit By Colorweb : 2012-11-01

if($_SERVER[’REQUEST_METHOD’]==’POST’) { // Upload is complete
if(!is_dir(NICUPLOAD_PATH) || !is_writable(NICUPLOAD_PATH)) {
nicupload_error(’Upload directory ’.NICUPLOAD_PATH.’ must exist and have write permissions on the server’);
}

$file = $_FILES[’image’];
$image = $file[’tmp_name’];

$max_upload_size = ini_max_upload_size();
if(!$file) {
nicupload_error(’Must be less than ’.bytes_to_readable($max_upload_size));
}

$ext = strtolower(substr(strrchr($file[’name’], ’.’), 1));
@$size = getimagesize($image);
if(!$size || !in_array($ext, $nicupload_allowed_extensions)) {
nicupload_error(’Invalid image file, must be a valid image less than ’.bytes_to_readable($max_upload_size));
}

$id = md5_file($image);
$filename = $id.”.”.$ext;

// Edit By Colorweb : 2012-11-01
$_UPLOAD_DIR = $d.’/tmp’;
$path = NICUPLOAD_PATH.’/’.$_UPLOAD_DIR.’/’.$filename;

$_CUT_UPLOAD_DIR = explode(”/”, $_UPLOAD_DIR);

for($i=0; $i<sizeof($_CUT_UPLOAD_DIR); $i++) { $_SET_DIR .= $_CUT_UPLOAD_DIR[$i].”/”; if(!is_dir(NICUPLOAD_PATH.’/’.$_SET_DIR)) { @mkdir(NICUPLOAD_PATH.’/’.$_SET_DIR, 0777); @chmod(NICUPLOAD_PATH.’/’.$_SET_DIR, 0777); } } // Edit By Colorweb : 2012-11-01 if(!move_uploaded_file($image, $path)) { nicupload_error(’Server error, failed to move file’); } if($rfc1867) { $status = apc_fetch(’upload_’.$id); } if(!$status) { $status = array(); } // $status[’done’] = 1; // $status[’width’] = $size[0]; // $status[’url’] = nicupload_file_uri($filename); if($rfc1867) { apc_store(’upload_’.$id, $status); } $status[”upload”][”image”][”name”] = $filename; $status[”upload”][”image”][”title”] = null; $status[”upload”][”image”][”caption”] = null; $status[”upload”][”image”][”hash”] = $id; $status[”upload”][”image”][”deletehash”] = ””; $status[”upload”][”image”][”datetime”] = date(’Y-m-d H:i:s’); $status[”upload”][”image”][”type”] = $size[”mime”]; $status[”upload”][”image”][”animated”] = ”false”; $status[”upload”][”image”][”width”] = $size[0]; $status[”upload”][”image”][”height”] = $size[1]; $status[”upload”][”image”][”size”] = filesize($image); $status[”upload”][”image”][”views”] = 0; $status[”upload”][”image”][”bandwidth”] = 0; $status[”upload”][”links”][”original”] = ”http://”.$_SERVER[”HTTP_HOST”].nicupload_file_uri($filename, $_UPLOAD_DIR); $status[”upload”][”links”][”imgur_page”] = ”http://”.$_SERVER[”HTTP_HOST”].nicupload_file_uri($filename, $_UPLOAD_DIR); $status[”upload”][”links”][”delete_page”] = null; $status[”upload”][”links”][”small_square”] = ”http://”.$_SERVER[”HTTP_HOST”].nicupload_file_uri($filename, $_UPLOAD_DIR); $status[”upload”][”links”][”large_thumbnail”] = ”http://”.$_SERVER[”HTTP_HOST”].nicupload_file_uri($filename, $_UPLOAD_DIR); nicupload_output($status, $rfc1867); exit; } else if(isset($_GET[’check’])) { // Upload progress check $check = $_GET[’check’]; if(!is_numeric($check)) { nicupload_error(’Invalid upload progress id’); } if($rfc1867) { $status = apc_fetch(’upload_’.$check); if($status[’total’] > 500000 && $status[’current’]/$status[’total’] < 0.9 ) { // Large file and we are < 90% complete $status[’interval’] = 3000; } else if($status[’total’] > 200000 && $status[’current’]/$status[’total’] < 0.8 ) { // Is this a largeish file and we are < 80% complete $status[’interval’] = 2000; } else { $status[’interval’] = 1000; } nicupload_output($status); } else { $status = array(); // $status[’noprogress’] = true; foreach($nicupload_allowed_extensions as $e) { if(file_exists(NICUPLOAD_PATH.’/’.$check.’.’.$e)) { $ext = $e; break; } } if($ext) { // $status[’url’] = nicupload_file_uri($check.’.’.$ext); } nicupload_output($status); } } // UTILITY FUNCTIONS function nicupload_error($msg) { echo nicupload_output(array(’error’ => $msg));
}

function nicupload_output($status, $showLoadingMsg = false) {
$script = ’
try {
’.(($_SERVER[’REQUEST_METHOD’]==’POST’) ? ’top.’ : ’’).’nicUploadButton.statusCb(’.json_encode($status).’);
} catch(e) { alert(e.message); }
’;

if($_SERVER[’REQUEST_METHOD’]==’POST’) {
// echo ’’;
echo json_encode($status);
// Edit By Colorweb : 2012-11-01
if($_POST[”ie_type”] == ”Y”) {
echo ””;
}
// Edit By Colorweb : 2012-11-01
} else {
echo $script;
}

if($_SERVER[’REQUEST_METHOD’]==’POST’ && $showLoadingMsg) {

echo <<<END


Uploading…
Please wait

END;

}

exit;
}

function nicupload_file_uri($filename, $_UPLOAD_DIR) {
return NICUPLOAD_URI.’/’.$_UPLOAD_DIR.’/’.$filename;
}

function ini_max_upload_size() {
$post_size = ini_get(’post_max_size’);
$upload_size = ini_get(’upload_max_filesize’);
if(!$post_size) $post_size = ’8M’;
if(!$upload_size) $upload_size = ’2M’;

return min( ini_bytes_from_string($post_size), ini_bytes_from_string($upload_size) );
}

function ini_bytes_from_string($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The ’G’ modifier is available since PHP 5.1.0
case ’g’:
$val *= 1024;
case ’m’:
$val *= 1024;
case ’k’:
$val *= 1024;
}
return $val;
}

function bytes_to_readable( $bytes ) {
if ($bytes<=0) return ’0 Byte’; $convention=1000; //[1000->10^x|1024->2^x]
$s=array(’B’, ’kB’, ’MB’, ’GB’, ’TB’, ’PB’, ’EB’, ’ZB’);
$e=floor(log($bytes,$convention));
return round($bytes/pow($convention,$e),2).’ ’.$s[$e];
}
[/crayon]

nicEditor 의 js파일의 일부 입니다.
[crayon lang=”javascript” toolbar=”false”]
// Edit By Colorweb : 2012-11-01
var iframe_element = ””;
var old_action = ””;
var iframe_callback = function()

{
iframe_element.removePane();
try {
var res = JSON.parse(document.frames[’fileUpload_ie_frame’].document.body.innerText.replace(”parent.iframe_callback()”, ””));
} catch(e) {
return iframe_element.onError();
}
var el = document.getElementById(’fileUpload_ie_frame’);
var remElement = (el.parentNode).removeChild(el);
var el = document.getElementById(’image’);
var remElement = (el.parentNode).removeChild(el);
var el = document.getElementById(’ie_type’);
var remElement = (el.parentNode).removeChild(el);
iframe_element.onUploaded(res.upload);
}
// Edit By Colorweb : 2012-11-01
var nicUploadButton = nicEditorAdvancedButton.extend({

…. 중략 ….

uploadFile : function() {
// Edit By Colorweb : 2012-11-01
if(typeof window.FormData === ”undefined”) {

var ie_frame = new bkElement(’iframe’)
.setAttributes({ ’name’ : ’fileUpload_ie_frame’ })
.setAttributes({ ’id’ : ’fileUpload_ie_frame’ })
.appendTo(document.getElementById(this.ne.options.dataForm));

var input_type = new bkElement(’input’)
.setAttributes({ ’name’ : ’ie_type’ })
.setAttributes({ ’id’ : ’ie_type’ })
.setAttributes({ ’value’ : ’Y’ })
.appendTo(document.getElementById(this.ne.options.dataForm));

this.fileInput.appendTo(document.getElementById(this.ne.options.dataForm));

document.getElementById(’image’).style.display = ”none”;
document.getElementById(’fileUpload_ie_frame’).style.display = ”none”;
iframe_element = this;
old_action = document.getElementById(this.ne.options.dataForm).action;
document.getElementById(this.ne.options.dataForm).target = ”fileUpload_ie_frame”;

document.getElementById(this.ne.options.dataForm).action = this.ne.options.uploadURI;
document.getElementById(this.ne.options.dataForm).submit();

document.getElementById(this.ne.options.dataForm).target = ””;
document.getElementById(this.ne.options.dataForm).action = old_action;

} else {
var file = this.fileInput.files[0];
if (!file || !file.type.match(/image.*/)) {
this.onError(”Only image files can be uploaded”);
return;
}
this.fileInput.setStyle({ display: ’none’ });
this.setProgress(0);

var fd = new FormData(); // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
fd.append(”image”, file);
fd.append(”key”, ”b7ea18a4ecbda8e92203fa4968d10660”);
var xhr = new XMLHttpRequest();
xhr.open(”POST”, this.ne.options.uploadURI || this.nicURI);

xhr.onload = function() {
try {
var res = JSON.parse(xhr.responseText);
} catch(e) {
return this.onError();
}
this.onUploaded(res.upload);
}.closure(this);
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) {
this.setProgress(e.loaded / e.total);
}.closure(this);
xhr.send(fd);
}
// Edit By Colorweb : 2012-11-01
},
[/crayon]

호출시 샘플 입니다.
[crayon lang=”javascript” toolbar=”false”]

bkLib.onDomLoaded(function() {
new nicEditors.allTextAreas({
iconsPath : ’/Editor/nicEditorIcons.gif’,
uploadURI : ’/Editor/nicUpload.php?d= // Editor가 있는 form의 이름 입니다.
// 반드시 dataFrom을 입력해야 IE에서 작동 합니다.
dataForm : ’input_form’

});
});

[/crayon]

 

Leave a Comment

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.