1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ProtoneMedia\LaravelMixins\Request; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\UploadedFile; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
|
9
|
|
|
trait ConvertsBase64ToFiles |
10
|
|
|
{ |
11
|
|
|
protected function base64FileKeys(): array |
12
|
|
|
{ |
13
|
|
|
return []; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Pulls the Base64 contents for each image key and creates |
18
|
|
|
* an UploadedFile instance from it and sets it on the |
19
|
|
|
* request. |
20
|
|
|
* |
21
|
|
|
* @return void |
22
|
|
|
*/ |
23
|
|
|
protected function prepareForValidation() |
24
|
|
|
{ |
25
|
|
|
Collection::make($this->base64FileKeys())->each(function ($filename, $key) { |
26
|
|
|
rescue(function () use ($key, $filename) { |
27
|
|
|
$base64Contents = $this->input($key); |
|
|
|
|
28
|
|
|
|
29
|
|
|
if (!$base64Contents) { |
30
|
|
|
return; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
// Generate a temporary path to store the Base64 contents |
34
|
|
|
$tempFilePath = tempnam(sys_get_temp_dir(), $filename); |
35
|
|
|
|
36
|
|
|
// Store the contents using a stream, or by decoding manually |
37
|
|
|
if (Str::startsWith($base64Contents, 'data:') && count(explode(',', $base64Contents)) > 1) { |
38
|
|
|
$source = fopen($base64Contents, 'r'); |
39
|
|
|
$destination = fopen($tempFilePath, 'w'); |
40
|
|
|
|
41
|
|
|
stream_copy_to_stream($source, $destination); |
|
|
|
|
42
|
|
|
|
43
|
|
|
fclose($source); |
|
|
|
|
44
|
|
|
fclose($destination); |
45
|
|
|
} else { |
46
|
|
|
file_put_contents($tempFilePath, base64_decode($base64Contents, true)); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$uploadedFile = new UploadedFile($tempFilePath, $filename, null, null, true); |
50
|
|
|
|
51
|
|
|
$this->request->remove($key); |
52
|
|
|
$this->files->set($key, $uploadedFile); |
53
|
|
|
}, null, false); |
54
|
|
|
}); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|