Michael de Silva's Blog

Software Engineer. Rubyist and Roboticist.

Michael de Silva's Blog

Software Engineer. Rubyist and Roboticist.

HOWTO: Image upload with Froala editor in Rails 4

All the pertinent info on how Froala makes the AJAX image upload are detailed on the Froala site.

The first challenge is to get around Rails' CSRF protection, and you can do this by passing the authenticity_token via the Rails helper form_authenticity_token.

          inlineMode: false,
          buttons: ["bold", "italic", "underline", "createLink", "insertImage", "undo", "redo", "html"],
          plainPaste: true,
          imageUploadURL: '<%= refinery.admin_upload_image_path %>',
          imageUploadParams: {
            authenticity_token: '<%= form_authenticity_token %>',
            return_to: window.location.href,
            site: '<%= current_site.id %>'
          imageErrorCallback: function (error) {
            console.log('ERROR: %O', error);

            var scroll_pos=(0);
            var message = error.message + ' (Code: ' + error.code + ')';
            var flash =  '<div id="flash_container"><div id="flash" class="flash flash_error" style="visibility: visible; opacity: 1;">'+ message +'</div></div>';

            $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
            }, 2000);

Your POST request's params hash will look similar to this; note that I have not included all the params passed.

=> {"authenticity_token"=>"t2zI9OyBKbWmPUPBI1pNTW4NKEKiefjeatfU/Y7JFjk=",
    "Content-Disposition: form-data; name=\"file\"; filename=\"category-portfolio-decor-bottles.jpg\"\r\nContent-Type: image/jpeg\r\n",

    # ...


Since the params[:file] will return the uploaded file params, it's quite simple to access te File instance via params[:file].instance_variable_get('@tempfile'); this can be passed to any Paperclip attachment or Dragonfly asset for easy persistance.

comments powered by Disqus