Quantcast
Viewing all articles
Browse latest Browse all 10

Rails IE Bug with Excel Mime Types

Came across a pretty interesting issue this week while trying to do some bugfixes for a project in IE6 and IE7.

The Rails project I’m working on has one action that accepts an *.xls format to deliver an excel spreadsheet to the user. Getting this to work is very simple, but for the sake of explanation here is the process.

Simply register the mime type in an initializer file

# config/initializers/mime_types.rb
Mime::Type.register "application/vnd.ms-excel", :xls

Then in your controller action’s respond_to block you can simply reference the new format:

# app/controllers/my_controller.rb
def my_action
  ...
  respond_to do |format|
    format.xls { send_file ... }
  end
end

Now, back to the “bug” or issue with IE6 and IE7. Every time a user hit that specific action with a regular request (not requesting the *.xls format), they received both the expected HTML output AND the xls format output.

Naturally, I don’t want to bombard the user with an IE popup dialog asking them to download an Excel file when they aren’t requesting one.

A quick trip to Google turned up this old Rails ticket. The issue appears to be with how IE6 and IE7 set their HTTP_ACCEPT headers:

image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, */*

There are two easy work-around solutions.

First, you can manually check and set the format param for IE requests:

before_filter :hijack_ie_default_format

def hijack_ie_default_format
  if request.user_agent =~ /MSIE/ and params['format'].nil?
    params['format'] = 'html'
  end
end

However, be careful when doing this. If your action can also accept AJAX ( text/javascript ) requests, then this will override that as well and set the format to return as HTML which is obviously not what you want. You would then end up spending a few hours wondering why IE6 and IE7 where returning javascript “Syntax Errors” on your AJAX actions.

What I ended up doing, since I needed that specific action to respond to javascript requests as well, was to simply extract the excel request into its own action. Sure this may be overkill and not very DRY, but it is still a proper solution. I just created a new #excel_export action and updated my excel links to point to the new action.


Viewing all articles
Browse latest Browse all 10

Trending Articles