For my client I have to use blob storage for some various files.
So I have created a independent bundle with a Blob class extends Doctrine\DBAL\Types\Type. and with a boot function in the bundle class.
That works pretty fine I can write in the database Blob datas.
But I can't download any document after :/
I have got:
public function downloadAction($id) {
$em = $this->getDoctrine()->getManager();
/* @var $entity Document */
$entity = $em->getRepository('Lille3SapBundle:Document')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Document entity.');
}
$file = $entity->getFichier();
$response = new \Symfony\Component\HttpFoundation\Response($file, 200, array(
'Content-Type' => 'application/octet-stream',
'Content-Length' => sizeof($file),
'Content-Disposition' => 'attachment; filename="'.$entity->getNomDocument().'"',
));
return $response;
}
and I have got an Exception: The Response content must be a string or object implementing __toString(), "resource" given.
in fact, the $file values is not the expected BLOB but something like Resource id #123
-> I have check blob data fields values, and they are ok in the database
So how can I force in the controller to have the blob row and not a Resource id #111
You can still use BLOB field for your field in DB as you initially planned.
In createAction store data as usual (with no base64_encode()):
$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(stream_get_contents($stream));
and in downloadAction just use:
$file = $entity->getFichier();
$response = new \Symfony\Component\HttpFoundation\Response(stream_get_contents($file),
200,
array(
'Content-Type' => 'application/octet-stream',
'Content-Length' => sizeof($file),
'Content-Disposition' => 'attachment; filename="'.$entity->getNomDocument().'"',
));
return $response;
Explanation:
BLOB fields are treated as resource variable which have no __toString() implementation.
gettype($file) -> "resource"
get_resource_type($file) -> "stream"
stream_get_contents($file) makes the magic here: gets STRING content from resource variable.
Okay, I have got a (very uggly) solution:
Firstly: I changed the data type blob to text for the file attribute of Document entity.
Secondly: in createAction I've changed the setFichier call:
$stream = fopen($entity->getFichier(),'rb');
$entity->setFichier(base64_encode(stream_get_contents($stream)));
Thirdly: in downloadAction, I decode the text base64 text field:
$file = $entity->getFichier();
$response = new \Symfony\Component\HttpFoundation\Response(base64_decode($file), 200, array(
'Content-Type' => 'application/octet-stream',
'Content-Length' => sizeof($file),
'Content-Disposition' => 'attachment; filename="'.$entity->getNomDocument().'"',
));
return $response;
And now I can persist and download files as blob way...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With