Image Upload for Redactor with Ruby on Rails

Redactor is an awesome wysiwyg editor, and one of its features is image uploading. To do that, according to their (also awesome) documentation, you need to setup a service to receive a post request with the image to upload, and respond with a specific json.

The implementation of that service on your existent Ruby on Rails application is fairly simple. I’ll assume you have basic Rails knowledge, and you’re familiar with Carrierwave, a Ruby library to handle file uploads. Also, I’ll be presenting an example code.

So, first step, you may need to generate a controller to handle that service.

rails g controller images

Next, setup a route for it:

post 'images/upload', to: 'images#upload_image', as: 'upload_image'

A sample code for the controller may be as such:

class ImagesController < ApplicationController
  skip_before_filter :verify_authenticity_token, only: [:upload]
  def upload
    uploader = TemporaryImageUploader.new #your uploader
    uploader.store!(params[:file])
    file_url = request.protocol + request.host_with_port + uploader.url
    render json: [{ filelink: file_url }]
  end
end

A few notes on the code above: please note the skip_before_filter part – without it, your app may lose the authentication session after the request from Redactor.

For the javascript, just add the imageUpload parameter and set it to your image_upload_url path, defined on the routes.

And that’s it.

Categorias: Javascript, Ruby on Rails