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.2And run:
bundle installThen Make sure to add this line just after //= require jquery //= require jquery_ujs :
//= require jquery.remotipartNow 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 endHandling 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 endHere we have tweaked the response body which is compatible with rails style. Thanks to Santosh for writing this post . Post Comments And Suggestions !!!