How do I create a download link from data in memory? 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?
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-&gt;headers-&gt;makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.txt'
    );

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

    return $response;
  }
}