| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace App\Traits;
- use Illuminate\Http\UploadedFile;
- use InvalidArgumentException;
- use RuntimeException;
- trait Base64ToFile
- {
- /**
- * Convert a base64 string to a file
- *
- * @param string $base64String The base64 encoded string
- * @param string $fileName Optional filename (without extension)
- * @return UploadedFile
- * @throws InvalidArgumentException If the base64 string is invalid
- * @throws RuntimeException If file creation fails
- */
- protected function convertBase64ToFile(string $base64String, ?string $fileName = null): UploadedFile
- {
- if (!preg_match('/^data:([^;]+);base64,(.+)$/', $base64String, $matches)) {
- throw new InvalidArgumentException('Invalid base64 string format');
- }
- $mimeType = $matches[1];
- $base64Content = $matches[2];
- $fileContent = base64_decode($base64Content, true);
- if ($fileContent === false) {
- throw new InvalidArgumentException('Failed to decode base64 content');
- }
- $extension = $this->getExtensionFromMimeType($mimeType);
- $fileName = $fileName ?? uniqid('file_', true);
- $fullFileName = "{$fileName}.{$extension}";
- $tempPath = sys_get_temp_dir() . '/' . $fullFileName;
- if (file_put_contents($tempPath, $fileContent) === false) {
- throw new RuntimeException('Failed to create temporary file');
- }
- return new UploadedFile(
- $tempPath,
- $fullFileName,
- $mimeType,
- null,
- true
- );
- }
- /**
- * Get file extension from mime type
- *
- * @param string $mimeType
- * @return string
- */
- private function getExtensionFromMimeType(string $mimeType): string
- {
- $mimeToExt = [
- 'image/jpeg' => 'jpg',
- 'image/png' => 'png',
- 'image/gif' => 'gif',
- 'application/pdf' => 'pdf',
- 'text/plain' => 'txt',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
- 'application/vnd.ms-excel' => 'xls',
- ];
- return $mimeToExt[$mimeType] ?? 'bin';
- }
- }
|