Support Center

How to open files uploaded using a File field, in a new window (target='_blank') in Drupal 7

Last Updated: Apr 12, 2014 03:02PM EEST
The following function will enable for you the option to open files in a new window based on the MIME type. Please paste the following code to your template.php file into your theme folder (sites/all/themes/THEMENAME/template.php) by replacing the THEMENAME to your theme name in the function title.
 
function THEMENAME_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  //open files of particular mime types in new window
  $new_window_mimetypes = array('application/pdf','text/plain','application/msword','image/jpeg','image/png');
  if (in_array($file->filemime, $new_window_mimetypes)) {
    $options['attributes']['target'] = '_blank';
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

 
Finally, you should clear all caches through Administration » Configuration » Performance » Clear all caches.


​Related Article


In case this article leaves any of your questions or concerns unanswered, please feel welcome to email us or post a public question.

​More than (just) Themes
http://www.morethanthemes.com/

Contact Us

[email protected]
http://assets2.desk.com/
false
morethanthemes
Loading
seconds ago
a minute ago
minutes ago
an hour ago
hours ago
a day ago
days ago
about
false
Invalid characters found
/customer/en/portal/articles/autocomplete