Skip to content

Instantly share code, notes, and snippets.

@wilcorrea
Last active May 9, 2018 18:07
Show Gist options
  • Save wilcorrea/d0245685858f92bfff061e189ee8054d to your computer and use it in GitHub Desktop.
Save wilcorrea/d0245685858f92bfff061e189ee8054d to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controller;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use function array_merge;
use function file_exists;
use function file_get_contents;
use function filemtime;
use function request;
use function view;
/**
* Class Download
* @package App\Http\Controllers\Web
*/
class Download extends Controller
{
/**
* @var array
*/
const HEADERS = [
'pdf' => [
'Content-Type' => 'application/pdf'
],
'jpg' => [
'Content-Type' => 'image/png'
],
'jpeg' => [
'Content-Type' => 'image/png'
],
'png' => [
'Content-Type' => 'image/png'
],
'mp3' => [
'Content-Type' => 'audio/mpeg'
],
'mp4' => [
'Content-Type' => 'video/mp4'
],
];
/**
* @param $file
* @return View|BinaryFileResponse
*/
function __invoke($file)
{
$filename = storage_path() . '/app/' . $file;
if (!file_exists($filename)) {
return view('page.410');
}
$info = pathinfo($filename);
$extension = $info['extension'];
$name = request()->get('name');
if (!$name) {
$name = 'document' . '.' . $extension;
}
$static = static::HEADERS;
$headers = isset($static[$extension]) ? $static[$extension] : ['Content-Type' => 'text/html'];
if (request()->get('download')) {
return response()->download($filename, $name, $headers);
}
/** @noinspection PhpUndefinedMethodInspection */
return Response::make(
file_get_contents($filename),
200,
array_merge($headers, ['Content-Disposition' => 'inline; filename="' . $name . '"'])
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment