You are here

public function FileController::download in File Entity (fieldable files) 8.2

Returns a HTTP response for a file being downloaded.

Parameters

FileInterface $file: The file to download, as an entity.

Return value

Response The file to download, as a response.

1 string reference to 'FileController::download'
file_entity.routing.yml in ./file_entity.routing.yml
file_entity.routing.yml

File

src/Controller/FileController.php, line 78

Class

FileController
Class FileController

Namespace

Drupal\file_entity\Controller

Code

public function download(FileInterface $file) {

  // Ensure there is a valid token to download this file.
  if (!$this
    ->config('file_entity.settings')
    ->get('allow_insecure_download')) {
    if (!isset($_GET['token']) || $_GET['token'] !== $file
      ->getDownloadToken()) {
      return new Response(t('Access to file @url denied', array(
        '@url' => $file
          ->getFileUri(),
      )), 403);
    }
  }
  $headers = array(
    'Content-Type' => Unicode::mimeHeaderEncode($file
      ->getMimeType()),
    'Content-Disposition' => 'attachment; filename="' . Unicode::mimeHeaderEncode($this->fileSystem
      ->basename($file
      ->getFileUri())) . '"',
    'Content-Length' => $file
      ->getSize(),
    'Content-Transfer-Encoding' => 'binary',
    'Pragma' => 'no-cache',
    'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
    'Expires' => '0',
  );

  // Let other modules alter the download headers.
  \Drupal::moduleHandler()
    ->alter('file_download_headers', $headers, $file);

  // Let other modules know the file is being downloaded.
  \Drupal::moduleHandler()
    ->invokeAll('file_transfer', array(
    $file
      ->getFileUri(),
    $headers,
  ));
  try {
    return new BinaryFileResponse($file
      ->getFileUri(), 200, $headers);
  } catch (FileNotFoundException $e) {
    return new Response(t('File @uri not found', array(
      '@uri' => $file
        ->getFileUri(),
    )), 404);
  }
}