Question

Is there a bundle, or a friendly way to generate or convert a file to its data URI representation in Symfony 2.3 or above and include it in a JSON response?

How can I do that?

Was it helpful?

Solution

While I'm not personally too familiar with Symfony, it's fairly easy to generate a base64 encoded data URI:

function base64_uri_file($file, $type = null)
{
    return base64_uri_data(file_get_contents($file), $type);
}

function base64_uri_data($data, $type = null)
{
    $type = $type ? : 'application/octet-stream';
    return sprintf('data:%s;base64,%s', $type, base64_encode($data));
}

This doesn't take into account errors or anything; you can handle that as you see fit. Anyway, then you can:

echo base64_uri_file('/windows/twain.dll', 'application/x-msdownload'); 
// data:application/x-msdownload;base64,TVqOAQEAAAAEAAAA//8AALgAAAAAAAAAQAAAAA...

Incorporate these calls into the response generation pipeline and you should be good.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top