Friday, June 17, 2011

Force download on clicking a link in Drupal

Forcing a file download when the user clicks on a link is pretty simple in Drupal.Few things you must already know
  • The files are generally stored in site/default/files folder. 
  • The data regarding the uploaded files are stored in files table in DB.
  • Every file has a unique fid.

All our downloads will happen through a single link. Our link will look like this
Download Image

Let us create a menu entry for our path "download/image". Lets pass the second argument to our function download_image() . This argument will be the unique fid.

$items['download/image/%'] = array(
    'title' => t('Download Images'),
    'page callback' => 'download_image',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK, 
    );

Our funciton download_image() that will actually force the file to be downloaded, rather than opening in a the brower. We accept fid as the argument to the function. We query the DB table for the filepath of the image based on the fid and we also make sure that it is an image as we don't want users to download other content types. Then we set the headers and make content dispostion as attachement(this is what forced the file to be downloaded) and then read the file from the path.

function download_image($fid) {
  global $user, $base_path, $base_url;
  if ($fid) {
    $query = db_query("SELECT filepath, filename FROM {files} WHERE fid = %d and filemime like '%image%' ", $fid);
    while ($files_data = db_fetch_array($query)) {
      $filepath = $base_url . "/" . $files_data['filepath'];
      $filename = $files_data['filename'];
        header("Content-Disposition: attachment; filename = $filename");
        readfile($filepath);
        exit();
    }
    drupal_set_message(t('You are not authorised to download this file'));
    drupal_goto();
  }  
}

No comments:

Post a Comment