Ajax File

Ajax file uploads on Rails

How to upload files with Ajax using Ruby on Rails?

Today we will see how to files upload using Ajax without a page load.

We will use DropzoneJS, DropzoneJS is an open-source library that provides drag ‘n’ drop file uploads with image previews.

At first, we need to install DropzoneJS gem on our rails environment, let’s try:

#=> Gemfile
gem 'dropzonejs-rails'

Then install via

$ bundle install

Then link to the pipeline

#=> app/assets/javascripts/application.js
//= require dropzone
#=> app/assets/stylshits/application.css
*= require dropzone/dropzone

And then migrate a model

$ rails generate model Photo avatar:string
$ rake db:migrate

Now we need install file uploader gem which is Carrierwave

#=> Gemfile
gem 'carrierwave'

Now generating uploader

$ rails generate uploader Avatar

app/uploaders/avatar_uploader.rb
#=> app/models/photo.rb
mount_uploader :avatar, AvatarUploader

Now create controller & view

$ rails g controller photos index

Configure routes

#=> config/routes.rb
resources :photos
#=> app/view/photos/index.html.erb
<%= form_tag photos_path, method: :post, class: "dropzone", id: "media-dropzone" do %>
   <%= file_field_tag :avatar, multiple: true%>
<% end %>
$(function() {
    var photoDropzone = new Dropzone("#media-dropzone");
    return photoDropzone.on("success", function(file, responseText) {
        var  = responseText.avatar.url;
    });
});
#=> app/controllers/photos_controller.rb
def create
    @avatar = Photo.new(avatar: params[:file])
    if @avatar.save
  respond_to do |format|
      format.json{render json: @avatar}
  end
    end
end

That’s it, now try to upload & look like below image

Happy coding!


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *