AJAX Image Uploads with Rails

Snippet Ruby on Rails jQuery

Last updated Feb 16, 2016

In this lesson, we will be creating an Image model that will process file uploads via AJAX. This lesson is going to use CarrierWave to handle uploads, but this can be adapted to work with other gems such as paperclip, dragonfly, or refile.

The main challenge is that browsers prevent file uploads with AJAX by default for security concerns. There are several workarounds, but the quickest solution is to use the remotipart gem.

Gemfile

gem 'carrierwave'
gem 'mini_magick'
gem 'remotipart', '~> 1.2'

Lesson Resources

Lesson Checkpoints

1. Enable CarrierWave File Uploads

console

$ rails g scaffold Image name:string file:string
$ rails g uploader Image

models/image.rb

class Image < ActiveRecord::Base
    mount_uploader :file, ImageUploader
end

assets/javascripts/application.js

//= require jquery.remotipart

2. Code the AJAX Image Upload

First, we need to make the Image form remote.

views/images/_form.html.erb

<%= form_for(@image, remote: true) do |f| %>

Next, we need to make sure the controller responds to JavaScript.

controllers/images_controller.rb

respond_to :js

Next, we need to create a partial that will render the uploaded image.

views/images/_image.html.erb

<%= @image.name %>
<%= image_tag(@image.file) %>

Lastly, we need to create a js.erb file to modify the DOM after the AJAX request is complete. To keep things simple, we are going to use jQuery to append the image after the form.

views/images/create.js.erb

$('form').append('<%= j render “image” %>');

3. Start Uploading

Now your form is ready to accept AJAX Image uploads. When you click the submit button, the uploaded image should be appended after the form.

image uploaded via AJAX with ruby on rails

Comments