Forcing download of mp3 and other files in browers

I needed a quick and dirty option for forcing an mp3 file to be downloaded after a set amount of time.

However, there appears to be a little issue, especially in Chrome (but probably in Firefox too), which prevents this from working quite as quickly as hoped.

Quick and dirty

I had assumed I could just use the old Javascript trick of

     <script>
          setTimeout(
              function () {window.location = 'path/to/file.mp3';}, 
              5000
          )
     </script>

The problem

However this caused an issue in Chrome where Chrome would actually load the file in the browser and start playing it with it’s built in HTML5 mp3 playback.

I knew the client would prefer to avoid this situation and just wants the end user to download the mp3 file, so I needed to find a solution.

The fix

After much searching around I found out that the best way to force the browser to download the file rather than opening it in the browser was to use a .htaccess directive to make the browser consider the file an ‘attachment’.

Now before modifying your .htaccess make sure that you’ve got the apache ‘headers’ module enabled. If you’re unsure whether it’s enabled or not, you can use the following command to check:

$ apache2ctl -M | grep header

If you get a result of:

headers_module (shared)

Then you already have it enabled. If not then you’ll need to enable it by running

$ sudo a2enmod headers
$ sudo service apache2 reload

Now that you have the headers module enabled you can edit the .htaccess file for your site to include:

<FilesMatch "\.(mov|mp3|pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>

Obviously you can update the list of different file types to suit your needs, but this example includes .mov, .mp3, and .pdf files. Please note that I found browser cache sometimes ignores the changed .htaccess but I could quickly confirm it was working by opening a private browser session and testing the page again.

Comments