Thursday, November 5, 2015

Upload Image using CKeditor - Rails

Hello Guys,

   Today i've configure CKeditor (https://github.com/galetahub/ckeditor) to my Rails application and i found there is no upload button along with Image insert dialog.
So i've modified the ckeditor/config.js to below and it then show new tab called 'Upload' in Image insert dialog.

See. config.js

CKEDITOR.editorConfig = function (config) {

  // ... other configuration ...
  config.language = 'en';
  config.toolbar_regular = [
    { name: 'document', items: ['Source'] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
    '/',
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'insert', items: ['Table', 'Image', 'HorizontalRule', 'SpecialChar' ] },
    '/',
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'tools', items: [ 'Maximize'] },
    { name: 'plugins', items: ['CodeSnippet', 'Cite'] }
  ];
  config.toolbar_lite = config.toolbar_regular.concat({ name: "lite", items: ["lite_ToggleShow", "lite_AcceptAll", "lite_RejectAll"] });
    config.toolbar = 'regular';
  config.allowedContent = true;
   /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";
  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";
  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();
    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];
      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }
    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }
    return params;
  };
  config.addQueryString = function( url, params ){
    var queryString = [];
    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }
    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };
  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;
    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));
      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });
};

Hope this article helps you.

2 comments:

  1. Hi priyanka. This post helps me a lot.

    There's one question that what the lines after '// Rails CSRF token' work for. I'm using 'galetahub/ckeditor' for adapter gem and it works well including image upload function without the lines after '// Rails CSRF token'.

    I'm wondering whether the lines are added to support AJAX or ajgularjs.

    Thanks.

    ReplyDelete
    Replies
    1. For the clarity, my config.js only includes 7 lines of starting with 'config.filebrowser...'.

      I'm not arguing which codes are useful or useless, but want to know which other lines are working for so that the lines need to be added or not.

      Thanks :-)

      Delete