2015/12/03

CKEditor Image Upload On Codeigniter

้€™็ฏ‡ๆ–‡็ซ ๆœƒไธ€ๆญฅๆญฅๅฏฆไฝœ CKEditor ๅœจ CodeIgniter ไธญๅœ–็‰‡ไปฅๅŠๆช”ๆกˆไธŠๅ‚ณๅˆฐ server ็š„ๅŠŸ่ƒฝ,้ฆ–ๅ…ˆๆˆ‘ๅ€‘ๅ‰ๅพ€ CKEditor ๅฎ˜็ถฒไธ‹่ผ‰ๆœ€ๆ–ฐ็š„็‰ˆๆœฌ,้€™ๅ€‹ demo ไฝฟ็”จ็š„ๆ˜ฏ 4.6,ๅญ˜ๆช”ๅพŒๆˆ‘ๆœƒๆ”พๅœจ assets/ckeditor/ ไธ‹,ๆˆ‘ๆœƒไฝฟ็”จ Sybio/ImageWorkshop ้€™ๅ€‹ๅฅ—ไปถๅฐๅœ–็‰‡ๅš็ฌฌไธ€ๆฌก็š„ๅฃ“็ธฎ,ๆˆ‘ๅ€‘้€šๅธธไธๅธŒๆœ› user ๅญ˜่ถ…ๅคง็š„ๆฑ่ฅฟๅœจๆˆ‘ๅ€‘้€™ๅ•ฆ,็•ข็ซŸไธๆ˜ฏ็›ธ็ฐฟ,ๅ‰ๅฐๅฏไปฅ้ †ๅˆฉ้กฏ็คบ็‚บๆบ–ๅ‰‡。

assets/ckeditor/config.js
CKEDITOR.editorConfig = function( config ) {
    config.toolbar =
        [
            {name:'document', items:['Source','-','Preview','Print']},
            {name:'clipboard', items:['Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo']},
            {name:'basicstyles', items:['Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat']},
            '/',
            {name:'paragraph', items:['NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl']},
            {name:'links', items:['Link','Unlink']},
            {name:'insert', items:['Image','Table']},
            {name:'tools', items:['Maximize']}
        ];
    config.enterMode = CKEDITOR.ENTER_BR;
    config.filebrowserImageUploadUrl = baseUrl + 'ckeditor/image_upload';
    config.filebrowserUploadUrl = baseUrl + 'ckeditor/file_upload';
};

้€™ๆ˜ฏๆˆ‘ๅธธ็”จ็š„ config,ๅทฅๅ…ทๅฏไปฅ่‡ช่กŒๅขžๆธ›。

application/views/ckeditor.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CKEditor Upload Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="assets/ckeditor/ckeditor.js"></script>
    <script src="assets/ckeditor/adapters/jquery.js"></script>
    <script type="text/javascript" charset="utf-8">
    var baseUrl = "<?php echo base_url(); ?>";
    window.CKEDITOR_BASEPATH = "<?php echo base_url('assets/ckeditor'); ?>";

    $(function() {
        $('.ckeditor').ckeditor();
    });
    </script>
</head>
<body>
<?php echo form_open_multipart('ckeditor/upload'); ?>
<?php echo form_textarea(['name' => 'content', 'class' => 'ckeditor']); ?>
<?php echo form_submit('submit', 'ไธŠๅ‚ณ'); ?>
<?php echo form_close(); ?>
</body>
</html>

็ฐกๅ–ฎ็š„่จญๅฎšไธ€ไธ‹ ckeditor ๅฟ…่ฆ็š„็’ฐๅขƒ。

application/controllers/Ckeditor.php
<?php

defined('BASEPATH') or exit('No direct script access allowed');

use PHPImageWorkshop\ImageWorkshop;

class Ckeditor extends CI_Controller
{
    /**
     * Upload path.
     *
     * @var string
     */
    private $path = 'assets/uploads/ckeditor/';

    /**
     * Index page.
     */
    public function index()
    {
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->view('ckeditor');
    }

    /**
     * CKEditor image upload
     *
     * Upload by ImageWorkshop package
     *
     * @return string
     */
    public function image_upload()
    {
        $this->load->helper('url');
        $funcNum = $this->input->get('CKEditorFuncNum');
        $source = $_FILES['upload']['tmp_name'];
        $file = $_FILES['upload']['name'];
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $ratio = 1200; // ๅฏฌๅบฆๆœ€ๅคงๆฏ”ไพ‹
        $allows = [1, 2, 3]; // GIF, JPEG, PNG
        $newName = date('YmdHis').rand(1000, 9999); //ๆ–ฐๆช”ๅ
        $message = '';
        $url = '';

        try {
            $exif = exif_imagetype($source);

            if (!$exif) {
                throw new Exception('ๆช”ๆกˆๆ ผๅผ้Œฏ่ชค');
            }

            if (!in_array($exif, $allows)) {
                throw new Exception('ๅƒ…ๅ…่จฑ gif, jpeg, png');
            }

            $imageInfo = getimagesize($source);
            $layer = ImageWorkshop::initFromPath($source);

            // ่‹ฅๅฏฌๅบฆๅคงๆ–ผๆฏ”ไพ‹,็ธฎๆ”พ็ฝฎๆฏ”ไพ‹
            if ($imageInfo[0] > $ratio) {
                $layer->resizeInPixel($ratio, null, true);
            }

            $fileName = "{$newName}.{$ext}";
            $layer->save($this->path, $fileName);
            $url = base_url($this->path.$fileName);
        } catch (Exception $e) {
            $message = $e->getMessage();
        }

        $string = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction({$funcNum}, '{$url}', '{$message}');</script>";

        $this->output
            ->set_content_type('text/html')
            ->set_output($string);
    }

    /**
     * CKEditor image upload
     *
     * @return string
     */
    public function file_upload()
    {
        $this->load->helper('url');
        $funcNum = $this->input->get('CKEditorFuncNum');
        $source = $_FILES['upload']['tmp_name'];
        $file = $_FILES['upload']['name'];
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $newName = date('YmdHis').rand(1000, 9999); //ๆ–ฐๆช”ๅ
        $message = '';
        $url = '';

        try {
            $fileName = "{$newName}.{$ext}";
            $target = $this->path.$fileName;

            if (move_uploaded_file($source, $target)) {
                $url = base_url($target);
            } else {
                $message = 'ไธŠๅ‚ณๅคฑๆ•—';
            }
        } catch (Exception $e) {
            $message = $e->getMessage();
        }

        $string = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction({$funcNum}, '{$url}', '{$message}');</script>";

        $this->output
            ->set_content_type('text/html')
            ->set_output($string);
    }
}

ๆˆ‘ๅ€‘ๅปบ็ซ‹ไบ† Ckeditor ็š„ controller,ๆŠŠ form ๆ”พๅœจ้ฆ–้ ,้€™ๅ€‹้ƒจไปฝๅŒ…ๅซไบ†ๅœ–็‰‡่ทŸๆช”ๆกˆไธŠๅ‚ณ็š„็จ‹ๅผ็ขผ,ๅœ–็‰‡้ƒจไปฝไนŸๅŒ…ๅซไบ†ๆช”ๆกˆๆ ผๅผๆชขๆŸฅ、ๆช”ๆกˆๅฐบๅฏธๆชขๆŸฅ,ๅฆ‚ๆžœ้‚„้œ€่ฆๆชขๆŸฅๆ›ดๅคš็š„ๆฑ่ฅฟๅฐฑๅœจ try catch ่ฃก้ขๅ†ๅŠ 。