Saturday, July 5, 2008

How to cause the IE to open specific application based on mime type

In general IE opens files based on their extensions. So when you try to access let's say http://localhost/myapp/helloWord.csv, it will open excel.

This is good, but now good enough, since the content on the web usually is not defined by file extensions, but by a content-type header. Especially in REST, when a resource can have different representations and we want same URL for resource:
http://localhost/myapp/helloWord should return HTML, http://localhost/myapp/helloWord?alt=application/atom+xml should return atom, http://localhost/myapp/helloWord?alt=text/csv should return csv and so on.
So what will happen if we ask for CSV in this way and server returned content-type=text/csv? The IE will not know how to handle such response and it will ask the user. However, we expect it to understand that this is CSV file and it should be opened by Excel. Right?

So there are two solutions for this problem:

1. Teach IE that mime text/csv should be mapped to the .csv file. This can be done in registry:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Mime\Database\Content Type\text/csv]
"Extension"=".csv"


By the way in this way you can map and mime to any extensions. Most of the mime already predefined, but some (like CSV) are missing.

2. Send Content-Disposition header.
If the response contains Content-Disposition: attachment; filename=HelloWorld.csv, it will cause the IE to open Excel. It happens since this header actually means that the response should be saved as HelloWorld.csv file.

Let's compare these two solutions:
First solution is better, when you cannot change the response. The response arrives, it doesn't contain Content-Disposition header, but it contains the proper mime type. So the mapping is done at client and this is fine.

The second solution is better, when you can change the server. It's obviously better to add additional header instead of changing registry of each client.

3 comments:

Conny Mac said...

a little miss understanding ...
how i can send a header if i've just link like :
bababa
if it's goes on apache (or other) server... it's not relevant. ;(

Tarlog said...

You can specify 'type' on your link: E.g. <a href="bababa" type="text/xml">Bababa</a>

Tarlog said...

Pay attention that 'type' is a hint. Meaning that is can be ignored by some servers/clients. But in general it should work.