Skip to content

Image File Upload to Server

Hyo Seong Choi edited this page Jan 2, 2016 · 1 revision

On January 1, 2016, summernote-rails was upgraded to the version 0.7.1.0 and 0.7.0.0 version was yanked due to its critical bugs.

Image file upload logic on Summernote editor is described on the following.

1. Project Environment

  • Ruby v2.3.0
  • Rails v4.2.5

2. Create Sample Project "Blog"

$ rails new blog

3. Adding gems into Gemfile

gem 'bootstrap-sass'     
gem 'font-awesome-rails' 
gem 'simple_form'
gem 'summernote-rails', '0.7.1.0'
gem 'codemirror-rails'
gem 'paperclip'

4. Setup

Install simple_form gem on the follows:

$ rails g simple_form:install --bootstrap

app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require codemirror
//= require codemirror/modes/ruby
//= require summernote
//= require summernote/locales/ko-KR
//= require turbolinks
//= require_tree .

app/assets/stylesheets/application.scss

@import "bootstrap";
@import "font-awesome";
@import "codemirror";
@import "summernote";
@import "codemirror/themes/solarized";

app/assets/javascripts/summernote_upload.coffee

sendFile = (file, toSummernote) ->
  data = new FormData
  data.append 'upload[image]', file
  $.ajax
    data: data
    type: 'POST'
    url: '/uploads'
    cache: false
    contentType: false
    processData: false
    success: (data) ->
      console.log 'file uploading...'
      toSummernote.summernote "insertImage", data.url

$(document).on 'page:change', (event) ->
  $('[data-provider="summernote"]').each ->
    $(this).summernote
      lang: 'ko-KR'
      height: 500
      codemirror:
        lineWrapping: true
        lineNumbers: true
        tabSize: 2
        theme: 'solarized'
      callbacks:
        onImageUpload: (files) ->
          sendFile files[0], $(this)
  return

Note : In the codeline No 15., when the link to the form view was clicked, for its correct working, summernote was called in the page:change event of document.

app/views/posts/_form.html.erb

<%= simple_form_for(@post) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :title %>
    <%= f.input :content, as: :summernote %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

Youtube demo

Source Code : https://github.com/luciuschoi/summernote071