|
7 | 7 | use Illuminate\Http\RedirectResponse; |
8 | 8 | use Symfony\Component\HttpFoundation\BinaryFileResponse; |
9 | 9 | use Symfony\Component\HttpFoundation\StreamedResponse; |
| 10 | +use Illuminate\Contracts\Filesystem\FileNotFoundException; |
10 | 11 | class StorageHelper |
11 | 12 | { |
12 | 13 | public static function downloader($filename, $disk = 'default') : BinaryFileResponse | RedirectResponse | StreamedResponse |
@@ -49,11 +50,40 @@ public static function allowSafeInline($file_with_path) { |
49 | 50 | 'png', |
50 | 51 | ]; |
51 | 52 |
|
52 | | - if (in_array(pathinfo($file_with_path, PATHINFO_EXTENSION), $allowed_inline)) { |
| 53 | + |
| 54 | + // The file exists and is allowed to be displayed inline |
| 55 | + if (Storage::exists($file_with_path) && (in_array(pathinfo($file_with_path, PATHINFO_EXTENSION), $allowed_inline))) { |
53 | 56 | return true; |
54 | 57 | } |
55 | | - |
56 | 58 | return false; |
57 | 59 |
|
58 | 60 | } |
| 61 | + |
| 62 | + /** |
| 63 | + * Decide whether to show the file inline or download it. |
| 64 | + */ |
| 65 | + public static function showOrDownloadFile($file, $filename) { |
| 66 | + |
| 67 | + $headers = []; |
| 68 | + |
| 69 | + if (request('inline') == 'true') { |
| 70 | + |
| 71 | + $headers = [ |
| 72 | + 'Content-Disposition' => 'inline', |
| 73 | + ]; |
| 74 | + |
| 75 | + // This is NOT allowed as inline - force it to be displayed as text in the browser |
| 76 | + if (self::allowSafeInline($file) != true) { |
| 77 | + $headers = array_merge($headers, ['Content-Type' => 'text/plain']); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + // Everything else seems okay, but the file doesn't exist on the server. |
| 82 | + if (Storage::missing($file)) { |
| 83 | + throw new FileNotFoundException(); |
| 84 | + } |
| 85 | + |
| 86 | + return Storage::download($file, $filename, $headers); |
| 87 | + |
| 88 | + } |
59 | 89 | } |
0 commit comments