Monday 27 April 2015

Textual Representation of logo

Asynchronous File Uploads in Rails

Today we will be uploading a file to server using ajax call with the help of Iframe method.
There is a Ruby Gem available called remotipart, which handles this kind of situation.
Installation
Installing is easy. Just add it to your Gemfile:
gem "remotipart", "~> 1.2" # Assusming in Rails > 3.2
And run:
bundle install
Then
Make sure to add this line just after //= require jquery //= require jquery_ujs :
//= require jquery.remotipart
Now you're ready to start uploading files.
In your controllers, views, or helpers, you may want to know if the form was submitted with Remotipart (using the iframe-transport) Remotipart makes a method available called remotipart_submitted :
if remotipart_submitted?

  # Upload files

else

  # Perform Simple Ajax Calls

end
Handling the Error:

In most blogs you will find to handle ajax complete and ajax success function when using remoti part bcoz remoti part internally submits your request as Iframe for which your js.erb template is not executed in rails fashion.

To do so , Here is a trick.
If you get your response wrapped in a text area do this.

Open up config/initializers

Create a file named remotipart_override.rb & paste the content.

module Remotipart

 module RenderOverrides

    def render_with_remotipart *args

      render_without_remotipart *args

      if remotipart_submitted?

        textarea_body = response.content_type == 'text/html' ? html_escape(response.body) : response.body

        response.body = textarea_body

        response.content_type = Mime::HTML

      end

      response_body

    end

  end

end
Here we have tweaked the response body which is compatible with rails style.


Thanks to Santosh for writing this post .


Post Comments And Suggestions !!!