Show the download dialog/popup when clicking a link, button, or image.

Public

Client requested that the relevant slide in a carousel should auto-download when clicked. Eventually, we integrated it also in our Schedule and Map images which are downloadable via a custom download button.

The idea of the mechanism is to have a download handler when a certain URL is accessed.
For example, when you have an image in `/sites/default/files/sample.png`, you'll now access it using the `/download-image/sample.png` in order to integrate the download dialog/popup.

There's also an alternative solution by inserting the HTML5's `download` attribute in the markup. Unfortunately, it is not a cross-browser solution. Hence, using PHP script is more reliable.

Get raw version
php
  1. /**
  2.  * Implements hook_menu().
  3.  */
  4. function mymodule_menu() {
  5. $items = array();
  6.  
  7. // Main URL is `/download-asset`.
  8. // For the `/download-asset/FILENAME` format,
  9. // it will pass the `FILENAME` as argument to the `_download_image()` handler.
  10. $items['download-asset'] = array(
  11. 'page callback' => '_download_image',
  12. 'access arguments' => array('access content'),
  13. 'type' => MENU_CALLBACK,
  14. );
  15.  
  16. return $items;
  17. }
  18.  
  19.  
  20. /**
  21.  * Sample Input URL: `/download-asset/sample.png`.
  22.  * It will then download the `sample.png` file from `/sites/default/files` folder.
  23.  */
  24. function _download_image($filename) {
  25. $public_image_url = 'public://' . $filename;
  26.  
  27. $headers = array(
  28. 'Content-type' => 'image/png',
  29. 'Content-Description' => 'File Transfer',
  30. 'Content-Disposition' => 'attachment; filename="' . $filename . '"' ,
  31. 'Content-length' => filesize($public_image_url),
  32. );
  33.  
  34. file_transfer($public_image_url, $headers);
  35. }

Click handler to redirect the URL to the download handler.

Get raw version
javascript
  1. (function ($) {
  2. Drupal.behaviors.downloader = {
  3. attach: function(context) {
  4. // Sample markup:
  5. // <div id="clickable-element" data-download-url="/download-asset/sample.png">
  6. $('#clickable-element').click(function() {
  7. window.location.href = $(this).data('download-url');
  8. return false;
  9. });
  10. }
  11. };
  12. })(jQuery);