Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an in memory file in Symfony

Tags:

php

symfony

I'm trying to return a BinaryFileResponse response in a Symfony Controller but it asks for a path or a File object. The thing is that I'm getting the file over a SOAP service, and it creates an object like this: filename + base64 encoded content + mime + extra stuff.

I don't really want to save it to disk then create the response...

Maybe I'm blinded at the moment, but is there any way to send it without creating a file in disk?

This is the action:

public function downloadAction($hash){
   $document = $this->get('soap_services.document_service')->findDocument($hash);

   return $this->file($SymfonyFileObjectOrPath, $fileName);
}

The $document object offers the following relevant methods: getMime, getName, getContent.

That's what I want to use to make a response without creating a File object (and the physical file that it implies).

like image 550
Astaroth Avatar asked Jan 23 '17 10:01

Astaroth


1 Answers

Hello maybe you should consider to just give a Response and force the download "manually".

// Generate response
$response = new Response();
$filename = 'yourFileName.txt';

// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', $yourMimeType );
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '";');
$response->headers->set('Content-length',  strlen($yourContentString));

// Send headers before outputting anything
$response->sendHeaders();

$response->setContent( $yourContentString );

return $response;

Maybe something like this will do the trick. Can you try this, maybe change it a little bit?

like image 91
Constantin Avatar answered Oct 08 '22 17:10

Constantin