3

I need to create a Controller that serves data as a download when accessed. That file is not in the file system but in memory; that's why I need a Controller instead of just serve file.

How do I create a download link from data in memory?

7

My approach is to use a Symfony Response obejct as explained here: The HttpFoundation Component: Serving files.

Firts setup the routing:

mymodule.download_item:
  path: '/myitems/{item_id}/download'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::downloadItem'

So the controller looks like:

class MyController extends ControllerBase {
 public function downloadItem($item_id) {

    $fileContent = functionToObtainExternalContent($item_id);
    $response = new Response($fileContent);

    $disposition = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.txt'
    );

    $response->headers->set('Content-Disposition', $disposition);

    return $response;
  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.