Base64ToFile.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Traits;
  3. use Illuminate\Http\UploadedFile;
  4. use InvalidArgumentException;
  5. use RuntimeException;
  6. trait Base64ToFile
  7. {
  8. /**
  9. * Convert a base64 string to a file
  10. *
  11. * @param string $base64String The base64 encoded string
  12. * @param string $fileName Optional filename (without extension)
  13. * @return UploadedFile
  14. * @throws InvalidArgumentException If the base64 string is invalid
  15. * @throws RuntimeException If file creation fails
  16. */
  17. protected function convertBase64ToFile(string $base64String, ?string $fileName = null): UploadedFile
  18. {
  19. if (!preg_match('/^data:([^;]+);base64,(.+)$/', $base64String, $matches)) {
  20. throw new InvalidArgumentException('Invalid base64 string format');
  21. }
  22. $mimeType = $matches[1];
  23. $base64Content = $matches[2];
  24. $fileContent = base64_decode($base64Content, true);
  25. if ($fileContent === false) {
  26. throw new InvalidArgumentException('Failed to decode base64 content');
  27. }
  28. $extension = $this->getExtensionFromMimeType($mimeType);
  29. $fileName = $fileName ?? uniqid('file_', true);
  30. $fullFileName = "{$fileName}.{$extension}";
  31. $tempPath = sys_get_temp_dir() . '/' . $fullFileName;
  32. if (file_put_contents($tempPath, $fileContent) === false) {
  33. throw new RuntimeException('Failed to create temporary file');
  34. }
  35. return new UploadedFile(
  36. $tempPath,
  37. $fullFileName,
  38. $mimeType,
  39. null,
  40. true
  41. );
  42. }
  43. /**
  44. * Get file extension from mime type
  45. *
  46. * @param string $mimeType
  47. * @return string
  48. */
  49. private function getExtensionFromMimeType(string $mimeType): string
  50. {
  51. $mimeToExt = [
  52. 'image/jpeg' => 'jpg',
  53. 'image/png' => 'png',
  54. 'image/gif' => 'gif',
  55. 'application/pdf' => 'pdf',
  56. 'text/plain' => 'txt',
  57. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
  58. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
  59. 'application/vnd.ms-excel' => 'xls',
  60. ];
  61. return $mimeToExt[$mimeType] ?? 'bin';
  62. }
  63. }