/** * Generates Download Response * * Verifies if file exists and file's type before generating the response. * * @param Event $event * @return BinaryFileResponse * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ private function generateDownloadResponse($event) { // Check if file exists $file = $event->getFileName(); $path = $this->get('kernel')->getRootDir() . '/../web/uploads/' . $file; if (!file_exists($path)) { throw $this->createNotFoundException(); } // Check the File Type: http://en.wikipedia.org/wiki/Internet_media_type $extArr = explode('.', $path); $ext = end($extArr); // Clean the filename $filename = preg_replace("/[^a-z0-9_\\s]+/i", "", $event->getName()) . '.' . $ext; $mimeType = mime_content_type($path); // Generate Response $response = new BinaryFileResponse($path); $response->headers->set('Content-Type', $mimeType); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename); return $response; }