-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathBulkUploadMediaFiles.php
More file actions
220 lines (184 loc) · 6.54 KB
/
BulkUploadMediaFiles.php
File metadata and controls
220 lines (184 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<?php
namespace App\Nova\Actions;
use App\MediaUpload;
use DigitalCreative\Filepond\Filepond;
use DigitalCreative\Filepond\Data\Data;
use Illuminate\Bus\Queueable;
use Illuminate\Http\UploadedFile;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Http\Requests\NovaRequest;
class BulkUploadMediaFiles extends Action
{
use InteractsWithQueue, Queueable, SerializesModels;
/**
* The displayable name of the action.
*
* @var string
*/
public $name = 'Bulk Upload Files';
/**
* Perform the action on the given models.
*
* @param \Laravel\Nova\Fields\ActionFields $fields
* @param \Illuminate\Support\Collection $models
* @return mixed
*/
public function handle(ActionFields $fields, Collection $models)
{
$uploadedFiles = $this->collectUploadedFiles($fields);
if (empty($uploadedFiles)) {
return Action::danger('Please select one or more files.');
}
$allowedExtensions = [
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg',
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt',
];
$uploaded = 0;
$skipped = 0;
foreach ($uploadedFiles as $file) {
if (!$file) {
$skipped++;
continue;
}
$originalName = $this->extractOriginalName($file);
if ($originalName === null) {
$skipped++;
continue;
}
$extension = strtolower((string) pathinfo($originalName, PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions, true)) {
$skipped++;
continue;
}
$baseName = pathinfo($originalName, PATHINFO_FILENAME);
$safeBaseName = Str::slug($baseName) ?: 'upload-file';
$destination = 'nova/uploads/' . now()->format('Y/m');
$finalFileName = $safeBaseName . '-' . Str::random(8) . '.' . $extension;
$storedPath = $this->storeFile($file, $destination, $finalFileName);
if (!$storedPath) {
$skipped++;
continue;
}
MediaUpload::create([
'title' => trim(str_replace(['-', '_'], ' ', $baseName)),
'file_path' => $storedPath,
'disk' => 'resources',
]);
$uploaded++;
}
return Action::message("Bulk upload completed: {$uploaded} uploaded, {$skipped} skipped.");
}
/**
* Get the fields available on the action.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function fields(NovaRequest $request): array
{
return [
Filepond::make('Files', 'files')
->multiple()
->limit(50)
->acceptedTypes('.jpg,.jpeg,.png,.gif,.webp,.svg,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt')
->rules('required')
->help('Drag and drop multiple files or click to select. Supported: images, PDF, Office docs, and TXT.'),
];
}
/**
* Collect uploaded files from Nova action fields + raw request payload.
*
* @return UploadedFile[]
*/
protected function collectUploadedFiles(ActionFields $fields): array
{
$candidates = [];
if (isset($fields->files)) {
$candidates[] = $fields->files;
}
$requestItems = request()->collect('files')->all();
if (!empty($requestItems)) {
$candidates[] = $requestItems;
}
$requestFiles = request()->allFiles();
if (!empty($requestFiles)) {
$candidates[] = $requestFiles;
}
$flatten = function ($value) use (&$flatten): array {
if ($value instanceof UploadedFile) {
return [$value];
}
if (is_string($value)) {
return [$value];
}
if (!is_array($value)) {
return [];
}
$result = [];
foreach ($value as $item) {
$result = array_merge($result, $flatten($item));
}
return $result;
};
$files = [];
foreach ($candidates as $candidate) {
$files = array_merge($files, $flatten($candidate));
}
return $files;
}
protected function extractOriginalName(UploadedFile|string $file): ?string
{
if ($file instanceof UploadedFile) {
return $file->getClientOriginalName();
}
try {
$data = Data::fromEncrypted($file);
return $data->filename;
} catch (\Throwable $e) {
return null;
}
}
protected function storeFile(UploadedFile|string $file, string $destination, string $finalFileName): ?string
{
if ($file instanceof UploadedFile) {
return $file->storeAs($destination, $finalFileName, 'resources');
}
try {
$data = Data::fromEncrypted($file);
} catch (\Throwable $e) {
return null;
}
$targetPath = $destination . '/' . $finalFileName;
$stream = Storage::disk($data->disk)->readStream($data->path);
if (is_resource($stream)) {
try {
$stored = Storage::disk('resources')->writeStream($targetPath, $stream, ['visibility' => 'public']);
} finally {
fclose($stream);
}
} else {
// Some environments return null instead of a stream for temp files.
// Fallback to reading file contents directly.
$contents = Storage::disk($data->disk)->get($data->path);
if (!is_string($contents) || $contents === '') {
Log::warning('[BulkUploadMediaFiles] Unable to read temp file contents', [
'disk' => $data->disk,
'path' => $data->path,
]);
return null;
}
$stored = Storage::disk('resources')->put($targetPath, $contents, 'public');
}
// Clean only this temp file. Deleting the whole directory can remove
// sibling files from the same multi-upload batch.
$data->deleteFile();
return $stored ? $targetPath : null;
}
}