Created
March 29, 2021 18:14
-
-
Save eduPHP/e344bda5c0b7bb19c13468791853cb55 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Requests; | |
| use Illuminate\Foundation\Http\FormRequest; | |
| use Illuminate\Http\UploadedFile; | |
| use Illuminate\Support\Arr; | |
| use Illuminate\Support\Facades\File; | |
| use Illuminate\Support\Str; | |
| class ImageUploadsFormRequest extends FormRequest | |
| { | |
| protected function prepareForValidation() | |
| { | |
| $input = $this->all(); | |
| if (!isset($input['image'])) { | |
| return; | |
| } | |
| if (Str::startsWith($input['image'], 'data:image')) { | |
| $file = $this->makeFromBase64($input['image']); | |
| $input['image'] = $file; | |
| } | |
| $this->replace($input); | |
| } | |
| protected function makeFromBase64($content) | |
| { | |
| $content = Arr::last(explode(',', $content)); | |
| $content = base64_decode($content); | |
| $mimeType = finfo_buffer(finfo_open(), $content, FILEINFO_MIME_TYPE); | |
| $extension = finfo_buffer(finfo_open(), $content, FILEINFO_EXTENSION); | |
| $size = strlen($content); | |
| $name = uniqid('img_') . '.' . $extension; | |
| $path = tempnam(sys_get_temp_dir(), uniqid('img-', true)); | |
| File::put($path, $content); | |
| return app(UploadedFile::class, [ | |
| 'path' => $path, | |
| 'originalName' => $name, | |
| 'mimeType' => $mimeType, | |
| 'size' => $size, | |
| 'error' => null, | |
| 'test' => true, | |
| ]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment