Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save banoodle/93e745b91ef6debbed42bd18705ae840 to your computer and use it in GitHub Desktop.
Save banoodle/93e745b91ef6debbed42bd18705ae840 to your computer and use it in GitHub Desktop.
Drupal 8 Media Entity Download custom patch
diff --git a/src/Controller/DownloadController.php b/src/Controller/DownloadController.php
index 09bfdf6..0735f54 100644
--- a/src/Controller/DownloadController.php
+++ b/src/Controller/DownloadController.php
@@ -7,11 +7,9 @@ use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Drupal\media\MediaInterface;
-use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpFoundation\ResponseHeaderBag;
+use Symfony\Component\HttpFoundation\File\MimeType\FileinfoMimeTypeGuesser;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;
-use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
@@ -80,81 +78,84 @@ class DownloadController extends ControllerBase {
* @throws NotFoundHttpException
*/
public function download(MediaInterface $media) {
- $bundle = $media->bundle();
- $source = $media->getSource();
- $config = $source->getConfiguration();
- $field = $config['source_field'];
-
- // This type has no source field configuration.
- if (!$field) {
- throw new \Exception("No source field configured for the {$bundle} media type.");
- }
-
- // If a delta was provided, use that.
- $delta = $this->requestStack->getCurrentRequest()->query->get('delta');
- // Get the ID of the requested file by its field delta.
- if (is_numeric($delta)) {
- $values = $media->{$field}->getValue();
+ // Get file entity to download.
+ $file = $this->getFileDownload($media);
+ $uri = $file->getFileUri();
- if (isset($values[$delta])) {
- $fid = $values[$delta]['target_id'];
- }
- else {
- throw new NotFoundHttpException("The requested file could not be found.");
- }
- }
- else {
- $fid = $media->{$field}->target_id;
+ // Or item does not exist on disk.
+ if (!file_exists($uri)) {
+ throw new NotFoundHttpException("The file {$uri} does not exist.");
}
- // If media has no file item.
- if (!$fid) {
- throw new NotFoundHttpException("The media item requested has no file referenced/uploaded in the {$field} field.");
+ $response = new BinaryFileResponse($uri);
+ $mimeTypeGuesser = new FileinfoMimeTypeGuesser();
+ if($mimeTypeGuesser->isSupported()){
+ $response->headers->set('Content-Type', $mimeTypeGuesser->guess($uri));
+ }else{
+ // Set the mimetype of the file manually, in this case for a text file is text/plain
+ $response->headers->set('Content-Type', 'text/plain');
}
- $file = $this->entityTypeManager()->getStorage('file')->load($fid);
-
- // Or file entity could not be loaded.
- if (!$file) {
- throw new \Exception("File id {$fid} could not be loaded.");
+ return $response;
}
- $uri = $file->getFileUri();
- $filename = $file->getFilename();
- $scheme = $this->streamWrapperManager->getScheme($uri);
+// throw new AccessDeniedHttpException();
+ /**
+ * Get file entity represent by by media.
+ *
+ * @param \Drupal\media\MediaInterface $media
+ * A valid media object.
+ *
+ * @return \Drupal\Core\Entity\EntityInterface
+ * File entity to download.
+ *
+ * @throws \Exception
+ * @throws NotFoundHttpException
+ */
+ public function getFileDownload(MediaInterface $media) {
+ $bundle = $media->bundle();
+ $source = $media->getSource();
+ $config = $source->getConfiguration();
+ $field = $config['source_field'];
+
+ // This type has no source field configuration.
+ if (!$field) {
+ throw new \Exception("No source field configured for the {$bundle} media type.");
+ }
- // Or item does not exist on disk.
- if (!$this->streamWrapperManager->isValidScheme($scheme) || !file_exists($uri)) {
- throw new NotFoundHttpException("The file {$uri} does not exist.");
- }
+ // If a delta was provided, use that.
+ $delta = $this->requestStack->getCurrentRequest()->query->get('delta');
- // Let other modules provide headers and controls access to the file.
- $headers = $this->moduleHandler()->invokeAll('file_download', [$uri]);
+ // Get the ID of the requested file by its field delta.
+ if (is_numeric($delta)) {
+ $values = $media->{$field}->getValue();
- foreach ($headers as $result) {
- if ($result == -1) {
- throw new AccessDeniedHttpException();
+ if (isset($values[$delta])) {
+ $fid = $values[$delta]['target_id'];
+ }
+ else {
+ throw new NotFoundHttpException("The requested file could not be found.");
+ }
+ }
+ else {
+ $fid = $media->{$field}->target_id;
}
- }
- if (count($headers)) {
- // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
- // sets response as not cacheable if the Cache-Control header is not
- // already modified. We pass in FALSE for non-private schemes for the
- // $public parameter to make sure we don't change the headers.
- $response = new BinaryFileResponse($uri, Response::HTTP_OK, $headers, $scheme !== 'private');
- if (empty($headers['Content-Disposition'])) {
- $response->setContentDisposition(
- ResponseHeaderBag::DISPOSITION_ATTACHMENT,
- $filename
- );
+ // If media has no file item.
+ if (!$fid) {
+ throw new NotFoundHttpException("The media item requested has no file referenced/uploaded in the {$field} field.");
}
- return $response;
- }
+ $file = $this->entityTypeManager()->getStorage('file')->load($fid);
- throw new AccessDeniedHttpException();
- }
+ // Or file entity could not be loaded.
+ if (!$file) {
+ throw new \Exception("File id {$fid} could not be loaded.");
+ }
+
+ return $file;
+
+ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment