Skip to content

Commit 06c599c

Browse files
committed
Added method to show or download file
Signed-off-by: snipe <[email protected]>
1 parent 6105323 commit 06c599c

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

app/Helpers/StorageHelper.php

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Illuminate\Http\RedirectResponse;
88
use Symfony\Component\HttpFoundation\BinaryFileResponse;
99
use Symfony\Component\HttpFoundation\StreamedResponse;
10+
use Illuminate\Contracts\Filesystem\FileNotFoundException;
1011
class StorageHelper
1112
{
1213
public static function downloader($filename, $disk = 'default') : BinaryFileResponse | RedirectResponse | StreamedResponse
@@ -49,11 +50,40 @@ public static function allowSafeInline($file_with_path) {
4950
'png',
5051
];
5152

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))) {
5356
return true;
5457
}
55-
5658
return false;
5759

5860
}
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+
}
5989
}

0 commit comments

Comments
 (0)