public function DownloadController::save in Media Download 1.0.x
Same name and namespace in other branches
- 1.2.x src/DownloadController.php \Drupal\media_download\DownloadController::save()
- 1.1.x src/DownloadController.php \Drupal\media_download\DownloadController::save()
Download the primary file resource referenced by the supplied media entity.
Parameters
\Drupal\media\MediaInterface $media: The media entity for which to initiate a file download.
Return value
\Drupal\media_download\CacheableBinaryFileResponse A cacheable binary file response.
File
- src/
DownloadController.php, line 74
Class
- DownloadController
- Adds support for direct downloads of media entities.
Namespace
Drupal\media_downloadCode
public function save(MediaInterface $media) {
$cacheability = new CacheableMetadata();
// Ensure that a file is referenced by the source field, and it exists.
if (empty($file = $this
->getFile($media))) {
throw new NotFoundHttpException("There is no file associated with the requested entity.");
}
// Add both the media entity and the file entity that it references as
// cacheable dependencies for this response.
$cacheability
->addCacheableDependency($file);
$cacheability
->addCacheableDependency($media);
// Create a new response object to download the requested file.
$response = new CacheableBinaryFileResponse($file
->getFileUri());
$response
->addCacheableDependency($cacheability);
$response
->setContentDisposition('inline');
// Clear the Cache-Control header so it can be calculated automatically.
$response->headers
->set('Cache-Control', '');
// Automatically calculate the ETag and Last-Modified headers.
$response
->setAutoEtag();
$response
->setAutoLastModified();
return $response;
}