-
-
Save fanorama/75da92b0c5fd0678a3a15ece18d0740e to your computer and use it in GitHub Desktop.
Laravel: create UploadedFile object from base64 string (autoremove temp file)
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\Helpers\File; | |
| use Illuminate\Http\File; | |
| use Illuminate\Http\UploadedFile; | |
| use Illuminate\Support\Arr; | |
| class FileHelper | |
| { | |
| public static function fromBase64(string $base64File): UploadedFile | |
| { | |
| // Get file data base64 string | |
| $fileData = base64_decode(Arr::last(explode(',', $base64File))); | |
| // Create temp file and get its absolute path | |
| $tempFile = tmpfile(); | |
| $tempFilePath = stream_get_meta_data($tempFile)['uri']; | |
| // Save file data in file | |
| file_put_contents($tempFilePath, $fileData); | |
| $tempFileObject = new File($tempFilePath); | |
| $file = new UploadedFile( | |
| $tempFileObject->getPathname(), | |
| $tempFileObject->getFilename(), | |
| $tempFileObject->getMimeType(), | |
| 0, | |
| true // Mark it as test, since the file isn't from real HTTP POST. | |
| ); | |
| // Close this file after response is sent. | |
| // Closing the file will cause to remove it from temp director! | |
| app()->terminating(function () use ($tempFile) { | |
| fclose($tempFile); | |
| }); | |
| // return UploadedFile object | |
| return $file; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment