2

I have a problem setting a correct path to symfony2 uploads directory.

I am trying to provide user with files that they previously uploaded.

Firstly I tried the following code:

$response = new Response();
        $d = $response->headers->makeDisposition(
         ResponseHeaderBag::DISPOSITION_ATTACHMENT,
         $document->getWebPath()
         );
         $response->headers->set('Content-Disposition', $d);

as advised in the cookbook and How to get web directory path from inside Entity?.

This however resulted in the following error:

 The filename and the fallback cannot contain the "/" and "\" characters. 

Therefore I decided to switch to:

     $filename = $this->get('kernel')->getRootDir() . '/../web' . $document->getWebPath();

     return new Response(file_get_contents($filename), 200, $headers);

this however results in:

Warning: file_get_contents(/***.pl/app/../web/uploads/documents/2.pdf) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: No such file or directory 

My file that I want to serve is located in

/web/uploads/documents/2.pdf

What code should I use to provide this file to end users?

Community
  • 1
  • 1
Abdel5
  • 1,112
  • 3
  • 16
  • 39

1 Answers1

2

In order to serve binary files, it's better to use the BinaryFileResponse, which accepts the absolute file path as its argument. The setContentDisposition() doesn't accept file paths but file names ... and that argument is optional (you should only use it in case you want to change the name of the file being served to end-users):

use Symfony\Component\HttpFoundation\BinaryFileResponse;

$response = new BinaryFileResponse($filePath);
$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName
); // This line is optional to modify file name

Regarding the file path, you can keep using the code you showed, but slightly changed:

$filePath = $this->container->getParameter('kernel.root_dir')
        .'/../web/'
        .$document->getWebPath();
Abdel5
  • 1,112
  • 3
  • 16
  • 39
Javier Eguiluz
  • 3,987
  • 2
  • 23
  • 44