Rails 3.2 Ajax Paperclip Image uploading

I was working on uploading images using paperclip gem . I wanted to use Ajax. I googled a lot, But every result says its not possible, that  you can't upload images using Ajax. Some Jquery plug-ins are available, But its not behaving like what I really needed in my project.

Finally I got the solution for this problem. It is a common solution. First of all download the the js code and save it as jquey.form.js in assets/javascripts. Include in application.js like

    //= require jquery.form

Next is your view. Which may look like this

    <div id="image_view">
      <%=image_tag @model.image_attr_name.url %>
    </div>


Next is your form to upload image
[You can use bootstrap modal to render this form. Then it'll be more beautiful]

    <%=form_for @model, :html => { :multipart => true, :id => "form_id" }, :url => url_for(:controller => 'controller', :action => 'method') do | f | %>
     Upload picture : <%= f.file_field image_attr_name %>
     <%= f.submit "Save changes", :id => :upload_pic %>
    <% end %>


Then add some javascript to the file where the form is rendered

    <script type="text/javascript">
      $(document).ready(function(){
        $('#upload_pic').click(function() {
          $("#form_id").ajaxForm({ target: "#image_view" }).submit(); // This line will display the ajax response in "image_view" div.
          //$("#modal_id").modal('hide'); if using modal uncomment this line to close current modal
          return false;
       });
     });
    </script>

Then write the method in corresponding controller

    def method
      @pic = Model.new( params[:model_name] )
      @pic.save    
      render :template => "corresponding_view_file(ie, like pictures/show)", :layout => false
    end


Note : You can use this method for submitting forms which handle fields of any data types. So if you guys have more fields, you can simply add those in the form and view file. Ajax will remain same.

Hope You people know how the model and Gemfile look like. I think It may help you. For any query please comment on the same thread. Thank you.

Comments

  1. Nice!!, i just have one question.. How can i do it if im in a Wizard? like
    <%= nested_form_for @player, :url => wizard_path do |f| %>

    ReplyDelete

Post a Comment

Popular posts from this blog

Rails Kaminari - Ajax pagination

Rails 4, MySQL, and Emoji (Mysql2::Error: Incorrect string value: '\xF0\x9F\x8C\x9D')