Force Files to Download Instead of Showing Up in the Browser

Last modified: March 30, 2009 - 03:42

Usually when a user goes goes to a file URL, the file will show in the browser if the browser supports it. Image files like png, gif, jpg almost always show in the browser. Archive files like zip, tar, and gzip almost are always downloaded. Some file types show up in some browsers but not others, svg files will display in Firefox and Safari, but not Internet Explorer 7. Internet Explorer will usually try to show Microsoft Word files (doc and docx) in the browser, while most other browsers will download it.

To add consistency or to force certain files to download, you can fix this by simply adding an .htaccess file to the files directory. Note this only works with Public downloads and an Apache web server.

Set up a Specific Files to Download

  1. First, setup your file field so that it saves into a separate directory. This will make it so that you will only force certain files to download and not affect the rest of the files on your Drupal site. Visit Administer -> Content management -> Content types (admin/content/types). Click "Manage fields" on the type that you want files to be forced to be downloaded. Add or edit a file field, under the "Path settings" fieldset, set a path for your files to be uploaded.

    Now files uploaded to that field will be saved in a separate folder under your sites files directory.

  2. FTP to your site and create a file named .htaccess in your files directory. Usually this will be sites/default/files/[name of the subdirectory from step 1]. In that file put the following lines:

    <FilesMatch "\.(?i:doc|odf|pdf|rtf|txt)$">
      Header set Content-Disposition attachment
    </FilesMatch>

    This particular example will force files with doc, odf, pdf, rtf, or txt to download instead of being shown in the browser.

  3. Upload a few files and (using the "Generic files" display setting), the files will be downloaded when the user clicks on the link.

Not sure if there is a syntax

Dinis - October 23, 2009 - 08:35

Not sure if there is a syntax error here, but this throws up a server error in any browser if I try this.

*edit* Fixed - mod_headers was not enabled on both webservers, enabling it allows the directive to work.

For Explorer that's not work

gagarine - November 6, 2009 - 20:24

For Explorer that's not work if an application is associated with this type..

One solution:

  <FilesMatch "\.(?i:pdf)$">
      ForceType application/octet-stream
      Header set Content-Disposition attachment
  </FilesMatch>

Source: http://www.thingy-ma-jig.co.uk/blog/06-08-2007/force-a-pdf-to-download

 
 

Drupal is a registered trademark of Dries Buytaert.