Laravel download base64 encoded files

David Carr

Laravel Framework Tutorials PHP & MySQL

Laravel has the ability to stream files from disc and remove them as soon as they've been downloaded. 

This snippet illustrates this ability. This is useful when you have binanry data that needs storing in order to be emailed and then removed afterwards: 

$attachment = EmailAttachment::where('id', $id)->first();
$path       = public_path($attachment->name);
$contents   = base64_decode($attachment->contentBytes);

//store file temporarily
file_put_contents($path, $contents);

//download file and delete it
return response()->download($path)->deleteFileAfterSend(true);

 

Copyright © 2006 - 2024 DC Blog - All rights reserved.