-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathFilepondController.php
executable file
·207 lines (175 loc) · 6.3 KB
/
FilepondController.php
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
<?php
namespace Sopamo\LaravelFilepond\Http\Controllers;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Sopamo\LaravelFilepond\Filepond;
class FilepondController extends BaseController
{
/**
* @var Filepond
*/
private $filepond;
public function __construct(Filepond $filepond)
{
$this->filepond = $filepond;
}
/**
* Uploads the file to the temporary directory
* and returns an encrypted path to the file
*
* @param Request $request
*
* @return \Illuminate\Http\Response
*/
public function upload(Request $request)
{
$inputName = $request->post('input_name') ?? config('filepond.input_name');
$input = $request->file($inputName);
if ($input === null) {
return $this->handleChunkInitialization();
}
$file = is_array($input) ? $input[0] : $input;
$path = config('filepond.temporary_files_path', 'filepond');
$disk = config('filepond.temporary_files_disk', 'local');
if (!($newFile = $file->storeAs($path . DIRECTORY_SEPARATOR . Str::random(), $file->getClientOriginalName(), $disk))) {
return Response::make('Could not save file', 500, [
'Content-Type' => 'text/plain',
]);
}
return Response::make($this->filepond->getServerIdFromPath($newFile), 200, [
'Content-Type' => 'text/plain',
]);
}
/**
* This handles the case where filepond wants to start uploading chunks of a file
* See: https://pqina.nl/filepond/docs/patterns/api/server/
*
* @param Request $request
* @return \Illuminate\Http\Response
*/
private function handleChunkInitialization()
{
$randomId = Str::random();
$path = config('filepond.temporary_files_path', 'filepond');
$disk = config('filepond.temporary_files_disk', 'local');
$fileLocation = $path . DIRECTORY_SEPARATOR . $randomId;
$fileCreated = Storage::disk($disk)
->put($fileLocation, '');
if (!$fileCreated) {
abort(500, 'Could not create file');
}
$filepondId = $this->filepond->getServerIdFromPath($fileLocation);
return Response::make($filepondId, 200, [
'Content-Type' => 'text/plain',
]);
}
/**
* Handle a single chunk
*
* @param Request $request
* @return \Illuminate\Http\Response
* @throws FileNotFoundException
*/
public function chunk(Request $request)
{
// Retrieve upload ID
$encryptedPath = $request->input('patch');
if (!$encryptedPath) {
abort(400, 'No id given');
}
try {
$finalFilePath = Crypt::decryptString($encryptedPath);
$id = basename($finalFilePath);
} catch (DecryptException $e) {
abort(400, 'Invalid encryption for id');
}
// Retrieve disk
$disk = config('filepond.temporary_files_disk', 'local');
// Load chunks directory
$basePath = config('filepond.chunks_path') . DIRECTORY_SEPARATOR . $id;
// Get patch info
$offset = $request->server('HTTP_UPLOAD_OFFSET');
$length = $request->server('HTTP_UPLOAD_LENGTH');
// Validate patch info
if (!is_numeric($offset) || !is_numeric($length)) {
abort(400, 'Invalid chunk length or offset');
}
// Store chunk
Storage::disk($disk)
->put($basePath . DIRECTORY_SEPARATOR . 'patch.' . $offset, $request->getContent(), ['mimetype' => 'application/octet-stream']);
$this->persistFileIfDone($disk, $basePath, $length, $finalFilePath);
return Response::make('', 204);
}
/**
* This checks if all chunks have been uploaded and if they have, it creates the final file
*
* @param $disk
* @param $basePath
* @param $length
* @param $finalFilePath
* @throws FileNotFoundException
*/
private function persistFileIfDone($disk, $basePath, $length, $finalFilePath)
{
$storage = Storage::disk($disk);
// Check total chunks size
$size = 0;
$chunks = $storage
->files($basePath);
foreach ($chunks as $chunk) {
$size += $storage
->size($chunk);
}
// Process finished upload
if ($size < $length) {
return;
}
// Sort chunks
$chunks = collect($chunks);
$chunks = $chunks->keyBy(function ($chunk) {
return substr($chunk, strrpos($chunk, '.') + 1);
});
$chunks = $chunks->sortKeys();
// Append each chunk to the final file
$data = '';
foreach ($chunks as $chunk) {
// Get chunk contents
$chunkContents = $storage
->get($chunk);
// Laravel's local disk implementation is quite inefficient for appending data to existing files
// To be at least a bit more efficient, we build the final content ourselves, but the most efficient
// Way to do this would be to append using the driver's capabilities
$data .= $chunkContents;
unset($chunkContents);
}
Storage::disk($disk)->put($finalFilePath, $data, ['mimetype' => 'application/octet-stream']);
Storage::disk($disk)->deleteDirectory($basePath);
}
/**
* Takes the given encrypted filepath and deletes
* it if it hasn't been tampered with
*
* @param Request $request
*
* @return mixed
*/
public function delete(Request $request)
{
$filePath = $this->filepond->getPathFromServerId($request->getContent());
$folderPath = dirname($filePath);
if (Storage::disk(config('filepond.temporary_files_disk', 'local'))->deleteDirectory($folderPath)) {
return Response::make('', 200, [
'Content-Type' => 'text/plain',
]);
}
return Response::make('', 500, [
'Content-Type' => 'text/plain',
]);
}
}