| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <?php
- namespace App\Traits;
- use Exception;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- trait UploadsBase64Image
- {
- /**
- * Upload a base64 encoded image and return the URL.
- *
- * @param string $base64Image
- * @param string $folder
- * @return string
- * @throws \Exception
- */
- public function uploadBase64Image(string $base64Image, string $folder): string
- {
- // Extract the file extension and base64 data
- if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
- $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);
- $type = strtolower($type[1]); // jpg, png, gif
- if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
- throw new Exception(__('validation.extensions', ['attribute' => __('general.image'), 'values' => 'jpg, jpeg, png, gif']));
- }
- $image = base64_decode($base64Image);
- if ($image === false) {
- throw new Exception('Base64 decode failed');
- }
- } else {
- throw new Exception('Invalid base64 image format');
- }
- // Generate a unique filename
- $filename = Str::random(20) . '.' . $type;
- // Define the full path where the file will be stored
- $filePath = $folder . '/' . $filename;
- // Save the file
- Storage::put($filePath, $image);
- // Return the URL of the uploaded image
- return Storage::url($filePath);
- }
- }
|