Forcing browsers to “open with..” or “save” attachments
There are times when you want to force web-browsers to handle a file differently to its default action. Specifically for me, I wanted browsers to not open certain text files themselves, but instead pass them to a text editor. Doing this is quite easy, but how is not well-known.
Obviously the immediate choice is to change the mime-type handling of the browser which is possible in Firefox, although not easily – I’m not sure if it’s possible in IE – but this has to be done manually for every browser. For Firefox you need to either get an extension for modifying the handlers, or you need to find a text file that has been forced into using the Open/Save dialogue (as per solution below) and then use the “Always perform this action” checkbox.
I decided to look at how the file is sent from the server as, often, when a txt file is passed from a CGI script, you get the Open/Save dialogue option. Although there are many different ways you can do it, the canonical way is for the server to pass a “Content-Disposition: attachment” response header to the browser which will stop it disposing of the file by opening within the browser regardless of the mime-type it sniffs from the file. As ALWAYS, Internet Explorer does not follow this rule and will often ignore the content-disposition header and act based on the mime-type it sniffs from the file regardless and so, to deal with IE you also need to force the mime-type to application/octet-stream.
This needs to be done in the Apache config, however the best way to do it is with .htaccess as it gives you directory-level control on the files you are affecting. Because it is being done with a regular expression being passed to the FilesMatch directive, you can choose to specify a particular file extension to affect as I have below, or you can specify a particular file, or anything else you can normally do with a regexp.
The following is the correct directive for a .htaccess file if you want to match any file with a .txt file extension, matching upper-case, lower-case or a mixture of cases. When matching the regexp, the mime-type is forced to “application/octet-stream” and the “Content-Disposition: attachment” header is passed.
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
You’re welcome

Recent Comments