Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Endpoint for Downloading Private Files

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $10.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

When we upload an article reference file, it successfully gets moved into the var/uploads/article_reference/ directory. That's great. And that means those files are not publicly accessible to anyone... which is what we wanted.

Listing the Uploaded References

Except... how can we allow authors to access them? As a first step, let's at least list the files on the page. In edit.html.twig, add a <ul> with some Bootstrap classes.

... lines 1 - 2
{% block content_body %}
... lines 4 - 7
<div class="row">
... lines 9 - 14
<div class="col-sm-4">
... lines 16 - 17
<ul class="list-group small">
... lines 19 - 23
</ul>
... lines 25 - 33
</div>
</div>
{% endblock %}
... lines 37 - 43

Then loop with {% for reference in article.articleReferences %}. Inside, add an <li>, a bunch of classes to make it look fancy, and then print, how about, reference.originalFilename.

... lines 1 - 2
{% block content_body %}
... lines 4 - 7
<div class="row">
... lines 9 - 14
<div class="col-sm-4">
... lines 16 - 17
<ul class="list-group small">
{% for reference in article.articleReferences %}
<li class="list-group-item d-flex justify-content-between align-items-center">
{{ reference.originalFilename }}
</li>
{% endfor %}
</ul>
... lines 25 - 33
</div>
</div>
{% endblock %}
... lines 37 - 43

This is pretty cool: when we move the files onto the server, we give them a weird filename. But because we saved the original filename, we can show that here: the author has no idea we're naming their files crazy things internally.

Let's see how this looks. Nice! 2 uploaded PDF's.

The Download Controller

To add a download link, we know that we can't just link to the file directly: it's not public. Instead, we're going to link to a Symfony route and controller and that controller will check security and return the file to the user. Let's do this in ArticleReferenceAdminController. Add a new public function, how about, downloadArticleReference().

... lines 1 - 17
class ArticleReferenceAdminController extends BaseController
{
... lines 20 - 78
public function downloadArticleReference(ArticleReference $reference)
{
... line 81
}
}

Add the @Route() above this with /admin/article/references/{id}/download - where the {id} this time is the id of the ArticleReference object. Then, name="admin_article_download_reference" and methods={"GET"}, just to be extra cool.

... lines 1 - 17
class ArticleReferenceAdminController extends BaseController
{
... lines 20 - 75
/**
* @Route("/admin/article/references/{id}/download", name="admin_article_download_reference", methods={"GET"})
*/
public function downloadArticleReference(ArticleReference $reference)
{
... line 81
}
}

Because the {id} is the id of the ArticleReference, we can add that as an argument: ArticleReference $reference. Just dd($reference) so we can see if this is working.

... lines 1 - 17
class ArticleReferenceAdminController extends BaseController
{
... lines 20 - 75
/**
* @Route("/admin/article/references/{id}/download", name="admin_article_download_reference", methods={"GET"})
*/
public function downloadArticleReference(ArticleReference $reference)
{
dd($reference);
}
}

Love it! Copy the route name and head back into the template. Add a <span> here for styling and an anchor with href="{{ path() }}", the route name, and id: reference.id. For the text, I'll use the Font Awesome download icon.

... lines 1 - 2
{% block content_body %}
... lines 4 - 7
<div class="row">
... lines 9 - 14
<div class="col-sm-4">
... lines 16 - 17
<ul class="list-group small">
{% for reference in article.articleReferences %}
<li class="list-group-item d-flex justify-content-between align-items-center">
... lines 21 - 22
<span>
<a href="{{ path('admin_article_download_reference', {
id: reference.id
}) }}"><span class="fa fa-download"></span></a>
</span>
</li>
{% endfor %}
</ul>
... lines 31 - 39
</div>
</div>
{% endblock %}
... lines 43 - 49

Try it out! Refresh and... download! So far so good.

Creating a Read File Stream

In some ways, our job in the controller is really simple: read the contents of the file and send it to the user. But... we don't actually want to read the contents of the file into a string and then put it in a Response. Because if it's a large file, that will eat up PHP memory.

This is already why, in UploaderHelper, we're using a stream to write the file. And now, we'll use a stream to read it. To keep all this streaming logic centralized in this class, add a new public function readStream() with a string $path argument and bool $isPublic so we know which of these two filesystems to read from.

... lines 1 - 12
class UploaderHelper
{
... lines 15 - 70
public function readStream(string $path, bool $isPublic)
{
... lines 73 - 81
}
... lines 83 - 110
}

Above the method, advertise that this will return a resource - PHP doesn't have a resource return type yet. Inside, step 1 is to get the right filesystem using the $isPublic argument.

... lines 1 - 12
class UploaderHelper
{
... lines 15 - 67
/**
* @return resource
*/
public function readStream(string $path, bool $isPublic)
{
$filesystem = $isPublic ? $this->filesystem : $this->privateFilesystem;
... lines 74 - 81
}
... lines 83 - 110
}

Then, $resource = $filesystem->readStream($path).

... lines 1 - 12
class UploaderHelper
{
... lines 15 - 67
/**
* @return resource
*/
public function readStream(string $path, bool $isPublic)
{
$filesystem = $isPublic ? $this->filesystem : $this->privateFilesystem;
$resource = $filesystem->readStream($path);
... lines 76 - 81
}
... lines 83 - 110
}

Tip

If you're using version 4 of oneup/flysystem-bundle (so, flysystem v2), you don't need to code defensively anymore! All methods will throw an exception automatically if the operation fails.

That's... pretty much it! But hold Cmd or Ctrl and click to see the readStream() method. Ah yes, if this fails, Flysystem will return false. So let's code defensively: if ($resource === false), throw a new \Exception() with a nice message:

Error opening stream for %s

and pass $path. At the bottom, return $resource.

... lines 1 - 12
class UploaderHelper
{
... lines 15 - 67
/**
* @return resource
*/
public function readStream(string $path, bool $isPublic)
{
$filesystem = $isPublic ? $this->filesystem : $this->privateFilesystem;
$resource = $filesystem->readStream($path);
if ($resource === false) {
throw new \Exception(sprintf('Error opening stream for "%s"', $path));
}
return $resource;
}
... lines 83 - 110
}

This is great! We now have an easy way to get a stream to read any file in our filesystems... which will work if the file is stored locally or somewhere else.

Checking Security

In the controller add the UploaderHelper argument. Oh, but before we use this, I forgot to check security! That was the whole point! The goal is to allow these files to be downloaded by anyone who has access to edit the article. We've been checking that via the @IsGranted('MANAGE') annotation - which leverages a custom voter we created in the Symfony series. We can use this annotation here because the article in the annotation refers to the $article argument to the controller.

But in this new controller, we don't have an article argument, so we can't use the annotation in the same way. No problem: add $article = $reference->getArticle() and then run the security check manually: $this->denyAccessUnlessGranted() with that same 'MANAGE' string and $article.

... lines 1 - 18
class ArticleReferenceAdminController extends BaseController
{
... lines 21 - 79
public function downloadArticleReference(ArticleReference $reference, UploaderHelper $uploaderHelper)
{
$article = $reference->getArticle();
$this->denyAccessUnlessGranted('MANAGE', $article);
... lines 84 - 92
}
}

Refresh to try it. We still have access because we're logged in as an admin.

Next, let's take our file stream and send it to the user! We'll also learn how to control the filename and force the user's browser to download it.

Leave a comment!

15
Login or Register to join the conversation
Cyril Avatar
Cyril Avatar Cyril | posted 3 years ago | edited

Hi! And thank you for this cast, it really helps!

I'm trying to make a "music on demand" service such as Spotify (a very very VERY small one ;-). Logged users can listening songs but I don't want them to download the original files. To to that, I tried to use the StreamResponse object as you did in the course:
`
$response = new StreamedResponse(function() use ($song, $uploaderHelper) {

$outputStream = fopen('php://output', 'wb');
$fileStream = $uploaderHelper->readStream($song->getFilePath(), false);
stream_copy_to_stream($fileStream, $outputStream);

});
`
This system is very cool because I can create a one-shot URL (with a token) as an endpoint to load the mp3 file in my page. And the real URL stays hidden.

But the download performances from s3 are very very VERY bad!

As I don't want users can download the original files, I think I can't use s3 presigned-URL... I really want to have a one-shot URL not one with expiration time.

Any idea?
Cyril (from France)

1 Reply

Hi Cyril S.!

Yes, the problem with "proxying" files of *any* significant size through a Symfony controller is that they will be *slow*. This is a great solution for things like PDF files... or something else. But videos or audio files, it's just not going to scale.

More generally, audio & video streaming are special "cases" - there are special protocols for doing this stuff - like RTMP or HLS https://en.wikipedia.org/wi... - and if you want a robust streaming services, you really need to do some research into this. I am definitely not an expert on it, so I can't say much unfortunately :).

But, if you are *generally* ok with streaming from S3 (or CloudFront in front of S3), then you will need to do signed URLs. However, you said this:

> This system is very cool because I can create a one-shot URL (with a token) as an endpoint to load the mp3 file in my page

You could *still* totally do this... but then the controller for this page would create a signed URL and redirect the user to that URL. So yes, the URL in the browser would ultimately be the signed URL to S3. But you would *still* be able to generate these one-shot URLs with a token and send them to people.

> As I don't want users can download the original files, I think I can't use s3 presigned-URL

If you want to avoid people downloading the files, then you *really* need to check into HLS or something like it - for example https://docs.aws.amazon.com... - streaming data to people... without actually allowing them to download the file is tricky business. Even with your current solution, I could use the one-shot URL to download the music file.

Cheers!

Reply
Cyril Avatar

In fact, with my current solution, the one-shot URL is not given to the user as this. It is calculated by the controller just before loading the page and destroyed just after. The *visible* URL in the media player is so unusable for downloading. It works great except the speed...
Thanks for your answer. I will check into HLS!

Reply
Ad F. Avatar

edit template is incomplete :)

1 Reply
Victor Avatar Victor | SFCASTS | Ad F. | posted 4 years ago | edited

Hey Ad F.

Thank you for reporting this! We had a bug with Emoji char, now it's fixed and all code blocks should be good. If you notice any problems with code blocks, please, let us know.

Cheers!

1 Reply
Simon L. Avatar
Simon L. Avatar Simon L. | posted 2 years ago | edited

Hi there !

When I use this :

<br />public function downloadArticleReference(ArticleReference $reference)<br />{<br />dd($reference);<br />}<br />

I have the following error :

<br />Cannot autowire argument $reference of "App\Controller\ArticleReferenceAdminController::downloadArticleReference()": it references class "App\Entity\ArticleReference" but no such service exists.<br />

To fix that, I have to use the following code instead :

`

public function downloadArticleReference($id, ArticleReferenceRepository $articleReferenceRepository)
{
    $reference = $articleReferenceRepository->findOneBy([
        'id' => $id,
    ]);
    dd($reference);
}

`

So I have 2 questions :

  1. What am I doing wrong ?
  2. Is my way to do good or not ?

Thanks for your help :)

Reply

Hey Stileex,

Unfortunately, ArticleReference and ArticleReferenceRepository are totally different things. We need to fetch the proper ArticleReference entity in that class. Well, you can fetch it from ArticleReferenceRepository manually, and then it will work well. But you can't just use ArticleReferenceRepository object as ArticleReference object in the code. If you see that error - most probably you misprint some namespaces in your projects. Make sure you use "Symfony\Component\Routing\Annotation\Route" in that controller, and make sure that "ArticleReference" class exists in src/Entity/ directory and has the same name and its namespace is "App\Entity". Also, do have "{id}" in your route path? It should be like this: '@Route("/admin/article/references/{id}/download", name="admin_article_download_reference", methods={"GET"})'

Btw, did you download the course code and started from start/ directory? Or did you started from scratch on a newer version of Symfony? Which version is it?

Cheers!

1 Reply
Simon L. Avatar
Simon L. Avatar Simon L. | Victor | posted 2 years ago | edited

Hi again Victor :)

So first, this is the reply to your last question: I have started my project test from the latest version of Symfony. I am not really using the course code, even if I have downloaded it and I am using it to check my own code. I think it's a better way to do, otherwise I would just copy paste what it is shown in the video, it forces me to fully understand what I am doing.

I have check everything you told me: Entity, Namespace, Route, the ID parameter, everything is here.

Maybe let me ask you my question in another way.

In the course code, you have this:

` /**

 * @Route("/admin/article/references/{id}/download", name="admin_article_download_reference", methods={"GET"})
 */
public function downloadArticleReference(ArticleReference $reference, S3Client $s3Client, string $s3BucketName)
{`

{id} is an integer (or could be a string in general)

But in the function downloadArticleReference you get it, then use it with the variable $reference which is an ArticleReference object.

How come you can do this ?? Is it a shortcut given by Symfony ?

That's why in my code, I fetch the object ArticleReferenceRepository manually with a database query first (using {id}).

Reply
Simon L. Avatar

And I had this problem because this component was not installed...
sensio/framework-extra-bundle

Reply

Hey Stileex,

Ah, yes! That "sensio/framework-extra-bundle" package should be installed to be able to use entity type-hint feature. Good catch!

Cheers!

Reply
Christina V. Avatar
Christina V. Avatar Christina V. | posted 3 years ago | edited

Hi !

I used some parts of this tutorial, including to upload some excel files.
The system of upload is working fine: in my particular case, the file is uploaded in <i>/var/uploads/import_user_file</i>

But I know need to use this excel file and I struggle for something:
In a controller or in a service, how can I retrieve the path to this file ?

I thought I could use the <i><b>function readStream()</b></i>

public function readStream(string $path, bool $isPublic)
{
        $filesystem = $isPublic ? $this->filesystem : $this->privateFilesystem;

        $resource = $this->filesystem->readStream($path);

        if ($resource === false) {
            throw new \Exception(sprintf('Error when opening stream for "%s" ', $path));
        }

        return $resource;

<b>And here in my controller:</b>

if ($file) {

                /** @var string $filename */
                $filename = $uploadHelper->uploadFile($file, UploadHelper::IMPORT_USER_FILE, false);

                // return "import_user_file/import-testing.xlsx"
                $path = UploadHelper::IMPORT_USER_FILE.'/'.$filename;

                $excelFile = $uploadHelper->readStream($path, false);

                dd($excelFile);
    

But... the dump return file not found, and of course, it looks like the proccess is not going to the folder /var/upload

Can somebody explain me, I think I miss something here.

Thanks!

Reply

Hey Caeema,

Well, it depends on what you need to do with that file. First of all, readStream() function returns you a resource. But if you need to get the content of that file - you probably may want to use file_get_contents() native PHP function to get the actual content of the file. But it might be memory consuming, working with resources might be more lightweight. But once again, it depends on what you're going to do with that excel file. If you have an Excel reader - a library you installed in your project - and that reader works with resources - probably it would be fine, just pass it the correct resource. But some readers may expect only path to the file, and they they will open it for reading/wringing themselves. It depends on the library API, etc.

But if you see that the file is not found - that probable mean that you path is incorrect. I'd recommend you to dump the path you specified in your controller and follow your filesystem manually to see that file there. Maybe it's incorrect and miss some folders in it, maybe you get doubled slash ("//") in it, maybe you forgot to pass an exceptions of the file, etc. So, first of all you need to make sure that the file really exists in the path you have in your controller.

I hope this helps!

Cheers!

Reply

2:42 I know, it is not frontend tutorial but for information: please don't forget about blind people and accessibility. Instead just icon, inside anchor put the whole text "Download %s", and replace %s with full name of the title.First: a11y screen readers are not able to read the icon. Second: "download" alone it's not fine, anchor text must be understandable outside of its context — a11y screen readers are able to generate list of all anchors of the website. If you want to hide the text for standard non-blind people, wrap it inside `span` but don't use display: none, use `sr-only` class instead of look for visually hidden technique if you don't use bootstrap in your project.

Reply

Hey TomaszGasior!

That's really great advice - and I should have done a better job on that - I don't mind being called out on something I could have done it better :). I will keep this in mind more on future tutorials - better accessibility is just a win for everything/everyone.

Cheers!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial is built on Symfony 4 but works great in Symfony 5!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.1.3",
        "ext-iconv": "*",
        "aws/aws-sdk-php": "^3.87", // 3.87.10
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "knplabs/knp-markdown-bundle": "^1.7", // 1.7.1
        "knplabs/knp-paginator-bundle": "^2.7", // v2.8.0
        "knplabs/knp-time-bundle": "^1.8", // 1.9.0
        "league/flysystem-aws-s3-v3": "^1.0", // 1.0.22
        "league/flysystem-cached-adapter": "^1.0", // 1.0.9
        "liip/imagine-bundle": "^2.1", // 2.1.0
        "nexylan/slack-bundle": "^2.0,<2.2.0", // v2.1.0
        "oneup/flysystem-bundle": "^3.0", // 3.0.3
        "php-http/guzzle6-adapter": "^1.1", // v1.1.1
        "sensio/framework-extra-bundle": "^5.1", // v5.2.4
        "stof/doctrine-extensions-bundle": "^1.3", // v1.3.0
        "symfony/asset": "^4.0", // v4.2.3
        "symfony/console": "^4.0", // v4.2.3
        "symfony/flex": "^1.9", // v1.17.6
        "symfony/form": "^4.0", // v4.2.3
        "symfony/framework-bundle": "^4.0", // v4.2.3
        "symfony/orm-pack": "^1.0", // v1.0.6
        "symfony/security-bundle": "^4.0", // v4.2.3
        "symfony/serializer-pack": "^1.0", // v1.0.2
        "symfony/twig-bundle": "^4.0", // v4.2.3
        "symfony/validator": "^4.0", // v4.2.3
        "symfony/web-server-bundle": "^4.0", // v4.2.3
        "symfony/yaml": "^4.0", // v4.2.3
        "twig/extensions": "^1.5" // v1.5.4
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.0", // 3.1.0
        "easycorp/easy-log-handler": "^1.0.2", // v1.0.7
        "fzaninotto/faker": "^1.7", // v1.8.0
        "symfony/debug-bundle": "^3.3|^4.0", // v4.2.3
        "symfony/dotenv": "^4.0", // v4.2.3
        "symfony/maker-bundle": "^1.0", // v1.11.3
        "symfony/monolog-bundle": "^3.0", // v3.3.1
        "symfony/phpunit-bridge": "^3.3|^4.0", // v4.2.3
        "symfony/profiler-pack": "^1.0", // v1.0.4
        "symfony/var-dumper": "^3.3|^4.0" // v4.2.3
    }
}
userVoice