We use headers and we have Laravel 5.1 but we do something a little different where we cache our files for a short time and create dynamic images of graphs using c3 plugin. At the end of my post I will show how we use these headers w/cache.
Make sure you add a route:
Route::get('/files/projects/{file}', 'DownloadController@index');
See this SO post
$file= public_path(). $name;
Laravel < 5
$headers = array(
'Content-Type: image/jpeg',
);
return Response::download($file, $name.'jpg', $headers);
Laravel >= 5
return response()->download($file, $name."jpg");
NOTE: Here is a cached image implementation ...(notice the base64_encode for binary files ie: .png .jpg)
$responseHeaders = array(
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Type' => 'image/png',
'Content-Disposition' => 'attachment; filename=' . $outputFileName . '.png',
'Expires' => '0',
'Pragma' => 'public'
);
$url = action('DownloadController@standAlone', ['cat' => $category]);
// Values cached for 1 minute... ???
if (Cache::has($url)){
return Response(base64_decode(Cache::get($url)))->withHeaders($responseHeaders);
} else {
$maxWidth = 2560;
$maxHeight = 854;
$minWidth = 780;
$minHeight = 260;
if ($height > $maxHeight) {
$height = $maxHeight;
}
if ($height < $minHeight) {
$height = $minHeight;
}
if ($width > $maxWidth) {
$width = $maxWidth;
}
if ($width < $minWidth) {
$width = $minWidth;
}
$command = app_path('bin/phantomjs');
$command .= ' ' . app_path('bin/maketrendpng.js');
$command .= ' ' . escapeshellarg($url);
$command .= ' /dev/stdout';
$command .= ' ' . escapeshellarg($height);
$command .= ' ' . escapeshellarg($width);
$command .= ' ' . request()->server->get('SERVER_NAME');
$command .= ' ' . escapeshellarg($_COOKIE[env('SESSION_COOKIE', 'laravel_session')]);
$command .= ' ' . escapeshellarg(env('SESSION_COOKIE', 'laravel_session'));
$handle = popen($command, 'r');
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
pclose($handle);
Cache::put($url, base64_encode($contents), 1);
return Response($contents)->withHeaders($responseHeaders);