How to implement nice image uploader to TinyMCE
Author:
Published: June 21, 2016
Time to read: 2 min
Nowadays, TinyMCE is considered to be one of the most popular text editors for HTML. The text editor has earned its popularity due to the following factors:
- easy to install
- comprehensive and clear documentation
- quite a large amount of plugins
TinyMCE + Rails 4
To work with TinyMCE in Rails application we recommend using gem tinymce-rails.
All the instruction for the installation of the gem is greatly described in the ReadMe:
However, we will pay our attention to the main points. Below is an example of the script tinyMCE.init
$(document).on 'page:load ready', ->
tinyMCE.init
plugins: ['image textcolor colorpicker codesample']
toolbar: 'forecolor backcolor | image | codesample'
selector: 'textarea.tinymce'
return
Where:
plugins
- list of included plugins
toolbar
- list and order of tools
selector
- HTML element, to which TinyMCE will be linked up
Ttypical mistake: if you’re using tinyMCE.init
, there is no need to create tinymce.yml
file.
TinyMCE has an image uploader which is not very convenient
We believe that one of the best solutions for this issue is a gem called tinymce-rails-imageupload.
Add to Gemfile
gem 'tinymce-rails-imageupload', github: 'PerfectlyNormal/tinymce-rails-imageupload'
now we have to replace plugin from image
to uploadimage
, this also applies to the toolbar.
So far, our script looks like:
$(document).on 'page:load ready', ->
tinyMCE.init
plugins: ['textcolor colorpicker codesample uploadimage']
toolbar: 'forecolor backcolor | uploadimage | codesample'
selector: 'textarea.tinymce'
return
The next step is to create an action for uploading images
def upload_image
upload = Cloudinary::Uploader.upload(params['file'])
render json: { image: { url: upload['url'] } }, content_type: 'text/html'
end
In this example, we’re using Cloudinary for uploading, but you’re free to use whatever technology you prefer. And don’t forget about router!
post '/tinymce_assets' => 'your_controller#upload_image'
Image uploader window:
Results:
Author:
Published: June 21, 2016
Time to read: 2 min
Share: