Skip to content

Instantly share code, notes, and snippets.

@waska14
Last active May 22, 2024 04:04
Show Gist options
  • Save waska14/8b3bcebfad1f86f7fcd3b82927576e38 to your computer and use it in GitHub Desktop.
Save waska14/8b3bcebfad1f86f7fcd3b82927576e38 to your computer and use it in GitHub Desktop.
Laravel: create UploadedFile object from base64 string (autoremove temp file)
<?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;
}
}
@MrEldin
Copy link

MrEldin commented Jul 6, 2023

Thank you!

@itCarl
Copy link

itCarl commented Aug 13, 2023

👍

@jeffamed
Copy link

Thank You... I helped it so much

@Tushar-Annexlogics
Copy link

it really helped a lot

@kitro
Copy link

kitro commented Jan 31, 2024

Thanks!

@funder7
Copy link

funder7 commented May 21, 2024

Perfetto!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment