UploadsBase64Image.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Traits;
  3. use Illuminate\Support\Facades\Storage;
  4. use Illuminate\Support\Str;
  5. trait UploadsBase64Image
  6. {
  7. /**
  8. * Upload a base64 encoded image to S3 and return the URL.
  9. *
  10. * @param string $base64Image
  11. * @param string $s3Folder
  12. * @return string
  13. * @throws \Exception
  14. */
  15. public function uploadBase64Image(string $base64Image, string $s3Folder): string
  16. {
  17. // Extract the file extension and base64 data
  18. if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
  19. $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);
  20. $type = strtolower($type[1]); // jpg, png, gif
  21. if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
  22. throw new \Exception(__('validation.extensions', ['attribute' => __('general.image'), 'values' => 'jpg, jpeg, png, gif']));
  23. }
  24. $image = base64_decode($base64Image);
  25. if ($image === false) {
  26. throw new \Exception('Base64 decode failed');
  27. }
  28. } else {
  29. throw new \Exception('Invalid base64 image format');
  30. }
  31. // Generate a unique filename
  32. $filename = Str::random(20) . '.' . $type;
  33. // Define the full path where the file will be stored
  34. $filePath = $s3Folder . '/' . $filename;
  35. // Save the file to S3
  36. Storage::disk('s3')->put($filePath, $image);
  37. // Return the URL of the uploaded image
  38. return Storage::disk('s3')->url($filePath);
  39. }
  40. }