setContentDisposition() public method

Sets the Content-Disposition header with the given filename.
public setContentDisposition ( string $disposition, string $filename = '', string $filenameFallback = '' ) : BinaryFileResponse
$disposition string ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
$filename string Optionally use this filename instead of the real name of the file
$filenameFallback string A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
return BinaryFileResponse
 public function invoiceAction(Convention $convention, Request $request)
 {
     $registrations = $convention->getRegistrations();
     $zip = new ZipArchive();
     $title = $convention->getSlug();
     $filename = tempnam('/tmp/', 'ritsiGA-' . $title . '-');
     unlink($filename);
     if ($zip->open($filename, ZIPARCHIVE::CREATE) !== true) {
         throw new \Exception("cannot open <{$filename}>\n");
     }
     if (false === $zip->addEmptyDir($title)) {
         throw new \Exception("cannot add empty dir {$title}\n");
     }
     $route_dir = $this->container->getParameter('kernel.root_dir');
     foreach ($registrations as $registration) {
         $single_file = $route_dir . '/../private/documents/invoices/' . $registration->getId() . '.pdf';
         if (false === file_exists($single_file)) {
             continue;
         }
         $name = $registration->getId();
         if (false === $zip->addFile($single_file, implode('/', array($title, $name . '.pdf')))) {
             throw new \Exception("cannot add file\n");
         }
     }
     if (false === $zip->close()) {
         throw new \Exception("cannot close <{$filename}>\n");
     }
     $response = new BinaryFileResponse($filename);
     $response->trustXSendfileTypeHeader();
     $response->prepare($request);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $convention->getSlug() . '-facturas.zip', iconv('UTF-8', 'ASCII//TRANSLIT', $convention->getSlug() . '-facturas.zip'));
     return $response;
 }
Ejemplo n.º 2
0
 public function connect(Application $app)
 {
     $route = $app['controllers_factory'];
     $route->get('{repo}/tree/{commitishPath}/', $treeController = function ($repo, $commitishPath = '') use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         if (!$commitishPath) {
             $commitishPath = $repository->getHead();
         }
         list($branch, $tree) = $app['util.routing']->parseCommitishPathParam($commitishPath, $repo);
         list($branch, $tree) = $app['util.repository']->extractRef($repository, $branch, $tree);
         $files = $repository->getTree($tree ? "{$branch}:\"{$tree}\"/" : $branch);
         $breadcrumbs = $app['util.view']->getBreadcrumbs($tree);
         $parent = null;
         if (($slash = strrpos($tree, '/')) !== false) {
             $parent = substr($tree, 0, $slash);
         } elseif (!empty($tree)) {
             $parent = '';
         }
         return $app['twig']->render('tree.twig', array('files' => $files->output(), 'repo' => $repo, 'branch' => $branch, 'path' => $tree ? $tree . '/' : $tree, 'parent' => $parent, 'breadcrumbs' => $breadcrumbs, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'readme' => $app['util.repository']->getReadme($repository, $branch, $tree ? "{$tree}" : "")));
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('commitishPath', $app['util.routing']->getCommitishPathRegex())->convert('commitishPath', 'escaper.argument:escape')->bind('tree');
     $route->post('{repo}/tree/{branch}/search', function (Request $request, $repo, $branch = '', $tree = '') use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         if (!$branch) {
             $branch = $repository->getHead();
         }
         $query = $request->get('query');
         $breadcrumbs = array(array('dir' => 'Search results for: ' . $query, 'path' => ''));
         $results = $repository->searchTree($query, $branch);
         return $app['twig']->render('search.twig', array('results' => $results, 'repo' => $repo, 'branch' => $branch, 'path' => $tree, 'breadcrumbs' => $breadcrumbs, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'query' => $query));
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('search');
     $route->get('{repo}/{format}ball/{branch}', function ($repo, $format, $branch) use($app) {
         $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo);
         $tree = $repository->getBranchTree($branch);
         if (false === $tree) {
             return $app->abort(404, 'Invalid commit or tree reference: ' . $branch);
         }
         $file = $app['cache.archives'] . DIRECTORY_SEPARATOR . $repo . DIRECTORY_SEPARATOR . substr($tree, 0, 2) . DIRECTORY_SEPARATOR . substr($tree, 2) . '.' . $format;
         if (!file_exists($file)) {
             $repository->createArchive($tree, $file, $format);
         }
         /**
          * Generating name for downloading, lowercasing and removing all non
          * ascii and special characters
          */
         $filename = strtolower($branch);
         $filename = preg_replace('#[^a-z0-9]#', '_', $filename);
         $filename = preg_replace('#_+#', '_', $filename);
         $filename = $filename . '.' . $format;
         $response = new BinaryFileResponse($file);
         $response->setContentDisposition('attachment', $filename);
         return $response;
     })->assert('format', '(zip|tar)')->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('archive');
     $route->get('{repo}/{branch}/', function ($repo, $branch) use($app, $treeController) {
         return $treeController($repo, $branch);
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('branch');
     $route->get('{repo}/', function ($repo) use($app, $treeController) {
         return $treeController($repo);
     })->assert('repo', $app['util.routing']->getRepositoryRegex())->bind('repository');
     return $route;
 }
 /**
  * @param AttachmentDto $attachmentDto
  * @return BinaryFileResponse
  */
 protected function getFileDownloadResponse(AttachmentDto $attachmentDto)
 {
     $response = new BinaryFileResponse($attachmentDto->getFilePath());
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $attachmentDto->getFileName(), iconv('UTF-8', 'ASCII//TRANSLIT', $attachmentDto->getFileName()));
     return $response;
 }
Ejemplo n.º 4
0
 /**
  * Create a new file download response.
  *
  * @param  \SplFileInfo|string  $file
  * @param  string  $name
  * @param  array   $headers
  * @param  null|string  $disposition
  * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
  */
 public static function download($file, $name = null, array $headers = array(), $disposition = 'attachment')
 {
     $response = new BinaryFileResponse($file, 200, $headers, true, $disposition);
     if (!is_null($name)) {
         return $response->setContentDisposition($disposition, $name, Str::ascii($name));
     }
     return $response;
 }
Ejemplo n.º 5
0
 public function loadApp()
 {
     $filename = 'stock-nth.apk';
     $headers = array();
     $disposition = 'attachment';
     $response = new BinaryFileResponse(storage_path() . '/' . $filename, 200, $headers, true);
     return $response->setContentDisposition($disposition, $filename, Str::ascii($filename));
 }
Ejemplo n.º 6
0
 /**
  * Create a new file download response.
  *
  * @param  SplFileInfo|string  $file
  * @param  int  $status
  * @param  array  $headers
  * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
  */
 public static function download($file, $name = null, $headers = array())
 {
     $response = new BinaryFileResponse($file, 200, $headers, true, 'attachment');
     if (!is_null($name)) {
         return $response->setContentDisposition('attachment', $name);
     }
     return $response;
 }
Ejemplo n.º 7
0
 public function RenderAction(\SW\DocManagerBundle\Entity\Document $document)
 {
     $path = $document->getPath();
     $response = new BinaryFileResponse($path);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $document->getName());
     return $response;
 }
 /**
  * @param Request $request
  *
  * @return BinaryFileResponse
  *
  * @throws HttpException
  */
 public function downloadAction(Request $request)
 {
     $document = new \SplFileInfo($this->resources . '/' . $request->get('fileName'));
     if (!$document->isReadable()) {
         throw new HttpException(404);
     }
     $response = new BinaryFileResponse($document);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $document->getFilename());
     return $response;
 }
 /**
  * @Route("/image/show/{id}", name="image_show")
  */
 public function showImageAction(Image $image = null)
 {
     if ($image) {
         $response = new BinaryFileResponse($image->getAbsolutePath());
         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $image->getName());
         return $response;
     } else {
         throw new NotFoundHttpException();
     }
 }
 /**
  * @param Request $request
  *
  * @return BinaryFileResponse
  *
  * @throws HttpException
  */
 public function downloadDocumentAction(Request $request)
 {
     $fileName = $request->get('fileName');
     $document = $this->meetings->findDocument($fileName);
     if (!$document) {
         throw new HttpException(404);
     }
     $response = new BinaryFileResponse($document);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $document->getFilename());
     return $response;
 }
Ejemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public function deliverFile($file, $filename = '', $disposition = self::DISPOSITION_INLINE, $mimeType = null, $cacheDuration = 0)
 {
     $response = new BinaryFileResponse($file);
     $response->setContentDisposition($disposition, $this->sanitizeFilename($filename), $this->sanitizeFilenameFallback($filename));
     $response->setMaxAge($cacheDuration);
     $response->setPrivate();
     if (null !== $mimeType) {
         $response->headers->set('Content-Type', $mimeType);
     }
     return $response;
 }
 /**
  * @Route("/{id}/download", name="article_review_download")
  * Función para descargar los artículos
  */
 public function downloadAction(ArticleReview $articleReview)
 {
     $this->denyAccessUnlessGranted('DOWNLOAD', $articleReview);
     $article = $articleReview->getArticle();
     $fileToDownload = $articleReview->getPath();
     $filename = $this->get('slugify')->slugify($article->getTitle()) . '.' . pathinfo($fileToDownload, PATHINFO_EXTENSION);
     $response = new BinaryFileResponse($fileToDownload);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename));
     return $response;
 }
 public function downloadAction()
 {
     $id = $this->request->query->get('id');
     /** @var Test $entity */
     $entity = $this->em->getRepository('AppBundle:Test')->find($id);
     $filename = sprintf("%s-%s-%s.%s", Slugger::slugify($entity->getSubject()->getName()), Slugger::slugify($entity->getSeason()), Slugger::slugify($entity->getYear()), pathinfo($entity->getFilename(), PATHINFO_EXTENSION));
     $fileToDownload = $this->get('vich_uploader.storage')->resolvePath($entity, 'file');
     $response = new BinaryFileResponse($fileToDownload);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename));
     return $response;
 }
Ejemplo n.º 14
0
 public function render(Request $request, Response $response, array $args)
 {
     $item = new Item($args['id']);
     $size = isset($args['size']) ? $args['size'] : 'o';
     $version = isset($args['version']) ? $args['version'] : null;
     $cacheFile = $item->getCachePath($size, $version);
     $fileResponse = new BinaryFileResponse($cacheFile);
     $fileResponse->headers->set('Content-Type', 'image/png');
     $fileResponse->setFile($cacheFile);
     $fileResponse->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $item->getTitle() . '.png');
     return $fileResponse;
 }
 public function download(Application $app, Request $request)
 {
     $fs = new Filesystem();
     $file = $request->query->get('file');
     $fullPath = $this->config['uploads']['base_directory'] . '/' . $file;
     if (!$fs->exists($fullPath)) {
         return new Response(null, Response::HTTP_NOT_FOUND);
     }
     $response = new BinaryFileResponse($fullPath);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, basename($fullPath));
     return $response;
 }
 /**
  * Download dataset.
  *
  * @param Request $request
  * @return Response
  */
 public function downloadAction(Request $request)
 {
     $manager = $this->get("accard.outcomes.manager");
     $givenFilename = $request->get("file");
     $filename = $manager->generateExportFilePath($givenFilename);
     if (!$givenFilename || !file_exists($filename) || !is_readable($filename)) {
         throw $this->createNotFoundException("Requested file is invalid, you may only download a file one time before it is deleted.");
     }
     $response = new BinaryFileResponse($filename);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $givenFilename);
     $response->deleteFileAfterSend(true);
     return $response;
 }
Ejemplo n.º 17
0
 /**
  * Serve the file using BinaryFileResponse.
  * 
  * @param string $date
  */
 public function vidAction($date)
 {
     $imageManager = $this->get('theapi_cctv.image_manager');
     try {
         $filename = $imageManager->getVideoFile($date);
         $response = new BinaryFileResponse($filename);
         $response->trustXSendfileTypeHeader();
         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename));
     } catch (\Exception $e) {
         throw $this->createNotFoundException($e->getMessage());
     }
     return $response;
 }
Ejemplo n.º 18
0
 public function download(VirtualProductOrderDownloadResponseEvent $event)
 {
     $orderProduct = $event->getOrderProduct();
     if ($orderProduct->getVirtualDocument()) {
         // try to get the file
         $path = THELIA_ROOT . ConfigQuery::read('documents_library_path', 'local/media/documents') . DS . "product" . DS . $orderProduct->getVirtualDocument();
         if (!is_file($path) || !is_readable($path)) {
             throw new \ErrorException(Translator::getInstance()->trans("The file [%file] does not exist", ["%file" => $orderProduct->getId()]));
         }
         $response = new BinaryFileResponse($path);
         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
         $event->setResponse($response);
     }
 }
 /**
  * Force download of the specified filename
  *
  * @Route("/download/{filename}", requirements={"filename": ".+"})
  *
  * @param $filename
  * @return BinaryFileResponse
  * @throws NotFoundException
  */
 public function downloadAction($filename)
 {
     $filePath = sprintf('%s/../web/media/%s', $this->get('kernel')->getRootDir(), $filename);
     // Check if requested file exists.
     $fs = new Filesystem();
     if (!$fs->exists($filePath)) {
         throw $this->createNotFoundException();
     }
     // Prepare BinaryFileResponse
     $response = new BinaryFileResponse($filePath);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
     return $response;
 }
Ejemplo n.º 20
0
 public function issueFileAction(IssueFile $issueFile)
 {
     $fileManager = $this->get('jb_fileuploader.file_history.manager');
     $rootDir = $this->getParameter('kernel.root_dir');
     $assetHelper = $this->get('templating.helper.assets');
     $fileHistory = $fileManager->findOneByFileName($issueFile->getFile());
     $path = $rootDir . '/../web' . $fileManager->getUrl($fileHistory);
     $path = preg_replace('/\\?' . $assetHelper->getVersion() . '$/', '', $path);
     $response = new BinaryFileResponse($path);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, preg_replace('/[[:^print:]]/', '_', $fileHistory->getOriginalName()));
     $event = new DownloadIssueFileEvent($issueFile);
     $dispatcher = $this->get('event_dispatcher');
     $dispatcher->dispatch(SiteEvents::DOWNLOAD_ISSUE_FILE, $event);
     return $response;
 }
Ejemplo n.º 21
0
 public function downloadAction($id)
 {
     $em = $this->getDoctrine()->getManager();
     $rep = $em->getRepository('GPSemellesBundle:Fichier');
     $fichier = $rep->find($id);
     if ($fichier) {
         $response = new BinaryFileResponse($fichier->getUploadDir() . '/' . $fichier->getFilename() . '.' . $fichier->getExtension());
         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fichier->getNom());
         return $response;
     } else {
         $request = $this->getRequest();
         $session = $request->getSession();
         $session->getFlashBag()->add('danger', 'Le fichier demandé est introuvable dans la base de données');
         return $this->redirectToRoute('semelles_index');
     }
 }
 /**
  * @ApiDoc(
  *  resource=true,
  *  description="Download a file test",
  *  https=true,
  *  requirements={
  *      {"name": "id", "dataType"="integer", "requirement"="\d+", "description"="Test id"},
  *  }
  * )
  * @Route("/tests/{id}/download")
  * @ParamConverter("test", class="AppBundle:Test", options={"mapping": {"id": "id"}})
  * @QueryParam(name="show", requirements="[01]", default="0", description="0: The file is downloaded, 1: The file is opened on the browser.")
  */
 public function getTestDownloadAction(Test $test, ParamFetcher $paramFetcher)
 {
     $filename = sprintf("%s-%s-%s.%s", Slugger::slugify($test->getSubject()->getName()), Slugger::slugify($test->getSeason()), Slugger::slugify($test->getYear()), pathinfo($test->getFilename(), PATHINFO_EXTENSION));
     $responseType = ResponseHeaderBag::DISPOSITION_ATTACHMENT;
     if ($page = $paramFetcher->get('show') === "1") {
         $responseType = ResponseHeaderBag::DISPOSITION_INLINE;
     }
     $fileToDownload = $this->get('vich_uploader.storage')->resolvePath($test, 'file');
     $response = new BinaryFileResponse($fileToDownload);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition($responseType, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename));
     $em = $this->getDoctrine()->getManager();
     $test->incrementDownloads();
     $em->persist($test);
     $em->flush();
     return $response;
 }
Ejemplo n.º 23
0
 /**
  * @param int $id
  * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  * @throws Core\Controller\Exception\ResultNotExistsException
  */
 public function execute($id)
 {
     if ($this->filesRepository->resultExists($id, $this->date->getCurrentDateTime()) === true) {
         $file = $this->filesCache->getCache($id);
         $path = $this->appPath->getUploadsDir() . 'files/';
         if (is_file($path . $file['file'])) {
             $ext = strrchr($file['file'], '.');
             $filename = $this->stringFormatter->makeStringUrlSafe($file['title']) . $ext;
             $response = new BinaryFileResponse($path . $file['file']);
             $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
             return $response;
         } elseif (preg_match('/^([a-z]+):\\/\\//', $file['file'])) {
             // External file
             return $this->redirect()->toNewPage($file['file']);
         }
     }
     throw new Core\Controller\Exception\ResultNotExistsException();
 }
Ejemplo n.º 24
0
 /**
  * Serve a file by forcing the download
  *
  * @Route("/download/{filename}", name="download_file", requirements={"filename": ".+"})
  */
 public function downloadFileAction($filename)
 {
     /**
      * $basePath can be either exposed (typically inside web/)
      * or "internal"
      */
     $basePath = $this->container->getParameter('kernel.root_dir') . '/Resources/uploads';
     $filePath = $basePath . '/' . $filename;
     // check if file exists
     $fs = new FileSystem();
     if (!$fs->exists($filePath)) {
         throw $this->createNotFoundException();
     }
     // prepare BinaryFileResponse
     $response = new BinaryFileResponse($filePath);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename));
     return $response;
 }
Ejemplo n.º 25
0
 protected function serveFile($filename, $displayName, Request $request, $asAttachment = false)
 {
     $lastModified = new \DateTime();
     $lastModified->setTimestamp(filemtime($filename));
     $ifModifiedSince = $request->headers->has('If-Modified-Since') ? new \DateTime($request->headers->get('If-Modified-Since')) : false;
     $finfo = finfo_open(FILEINFO_MIME_TYPE);
     $mimeType = finfo_file($finfo, $filename);
     $response = new BinaryFileResponse($filename);
     $response->setMaxAge(10);
     $response->headers->addCacheControlDirective('must-revalidate');
     $response->headers->set('Content-Type', $mimeType);
     $response->setLastModified($lastModified);
     $response->setContentDisposition($asAttachment ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE, $displayName, mb_convert_encoding($displayName, "ASCII", "UTF-8"));
     $response->prepare($request);
     if ($ifModifiedSince && $ifModifiedSince <= $lastModified) {
         $response->setStatusCode(304);
     }
     return $response;
 }
Ejemplo n.º 26
0
 public function download(VirtualProductOrderDownloadResponseEvent $event)
 {
     $orderProduct = $event->getOrderProduct();
     if ($orderProduct->getVirtualDocument()) {
         $baseSourceFilePath = ConfigQuery::read('documents_library_path');
         if ($baseSourceFilePath === null) {
             $baseSourceFilePath = THELIA_LOCAL_DIR . 'media' . DS . 'documents';
         } else {
             $baseSourceFilePath = THELIA_ROOT . $baseSourceFilePath;
         }
         // try to get the file
         $path = $baseSourceFilePath . DS . 'product' . DS . $orderProduct->getVirtualDocument();
         if (!is_file($path) || !is_readable($path)) {
             throw new \ErrorException(Translator::getInstance()->trans("The file [%file] does not exist", ["%file" => $orderProduct->getId()], VirtualProductDelivery::MESSAGE_DOMAIN));
         }
         $response = new BinaryFileResponse($path);
         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
         $event->setResponse($response);
     }
 }
Ejemplo n.º 27
0
 public function downloadExistingFile($filename, $fileFullPath)
 {
     $sessionData = new Session();
     $fs = new Filesystem();
     $file = $fileFullPath . $filename;
     if ($fs->exists($file . '.docx')) {
         $fullPath = $file . '.docx';
     } elseif ($fs->exists($file . '.doc')) {
         $fullPath = $file . '.doc';
     } elseif ($fs->exists($file . '.pdf')) {
         $fullPath = $file . '.pdf';
     } else {
         $sessionData->getFlashBag()->add('alert_danger', 'File not found!');
         return false;
     }
     $response = new BinaryFileResponse($fullPath);
     $response->trustXSendfileTypeHeader();
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename, iconv('UTF-8', 'ASCII//TRANSLIT', $filename));
     return $response;
 }
Ejemplo n.º 28
0
 /**
  * @Route("/data/file/{sha1}" , name="file.download")
  * @Method({"GET"})
  */
 public function downloadFileAction($sha1, Request $request)
 {
     $name = $request->query->get('name', 'upload.bin');
     $type = $request->query->get('type', 'application/bin');
     $file = false;
     foreach ($this->getParameter('storage_services') as $serviceName) {
         /**@var \AppBundle\Service\Storage\StorageInterface $service */
         $service = $this->get($serviceName);
         $file = $service->read($sha1);
         if ($file) {
             break;
         }
     }
     if (!$file) {
         throw new NotFoundHttpException('Impossible to find the item corresponding to this id: ' . $sha1);
     }
     $response = new BinaryFileResponse($file);
     $response->headers->set('Content-Type', $type);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $name);
     return $response;
 }
Ejemplo n.º 29
0
 /**
  * Download file.
  *
  * @param Request $request
  * @param Response $response
  *
  * @return BinaryFileResponse
  */
 public function index(Request $request, Response $response)
 {
     $key = $request->query->get('key', 'gp');
     $download = $request->query->get('download', '1');
     if ($download == '1') {
         $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT;
     } else {
         $disposition = ResponseHeaderBag::DISPOSITION_INLINE;
     }
     $metaFile = new \Molengo\MetaFile($response);
     $info = $metaFile->getInfo($key);
     $dataFile = $metaFile->getDataFileName($key);
     $fileName = $info['filename'];
     $headers = ['Pragma' => 'public', 'Content-Description' => 'File Transfer', 'Content-Transfer-Encoding' => 'binary', 'Expires' => '0', 'Cache-Control' => 'must-revalidate, post-check = 0, pre-check = 0'];
     $fileResponse = new BinaryFileResponse($dataFile, 200, $headers);
     $fileResponse->deleteFileAfterSend(false);
     $fileResponse->setContentDisposition($disposition, $fileName);
     $fileResponse->prepare($this->request);
     $fileResponse->sendContent();
     // Delete meta file after download
     $metaFile->delete($key);
     return $fileResponse;
 }
 /**
  * @param $id
  * @return Response
  * @Route("/reporte/download-file/{id}", name="ad_perfil_reporte_download")
  */
 public function downloadFileAction($id)
 {
     $em = $this->getDoctrine()->getManager();
     /** @var Archivo $file */
     $file = $em->getRepository('ADPerfilBundle:Archivo')->find($id);
     if (is_null($file)) {
         throw new NotFoundHttpException('Archivo No encontrado');
     }
     $response = new BinaryFileResponse($file->getPath());
     // Give the file a name:
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file->getNombre());
     return $response;
 }