feat: add base64 media registration method with support for multiple image formats and S3 storage
This commit is contained in:
parent
78965e9728
commit
66d6c843c3
@ -3,11 +3,58 @@
|
|||||||
namespace App\Services\Concerns;
|
namespace App\Services\Concerns;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||||
|
|
||||||
trait RegistersMedia
|
trait RegistersMedia
|
||||||
{
|
{
|
||||||
|
private function registerMediaFromBase64(
|
||||||
|
Model $model,
|
||||||
|
string $base64Data,
|
||||||
|
string $collectionName,
|
||||||
|
string $folder,
|
||||||
|
): void {
|
||||||
|
$dataUrl = $base64Data;
|
||||||
|
$mime = 'image/jpeg';
|
||||||
|
|
||||||
|
if (preg_match('/^data:(.+?);base64,/', $dataUrl, $matches)) {
|
||||||
|
$mime = $matches[1];
|
||||||
|
$dataUrl = preg_replace('/^data:.+?;base64,/', '', $dataUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
$binary = base64_decode($dataUrl, true);
|
||||||
|
|
||||||
|
if ($binary === false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$extension = match ($mime) {
|
||||||
|
'image/png' => 'png',
|
||||||
|
'image/webp' => 'webp',
|
||||||
|
'image/gif' => 'gif',
|
||||||
|
default => 'jpg',
|
||||||
|
};
|
||||||
|
|
||||||
|
$date = now()->format('Y/m/d');
|
||||||
|
$uuid = Str::uuid();
|
||||||
|
$key = "{$folder}/{$date}/{$uuid}/photo.{$extension}";
|
||||||
|
|
||||||
|
Storage::disk('s3')->put($key, $binary, [
|
||||||
|
'ContentType' => $mime,
|
||||||
|
'ACL' => 'public-read',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->registerMedia(
|
||||||
|
model: $model,
|
||||||
|
s3Key: $key,
|
||||||
|
collectionName: $collectionName,
|
||||||
|
mimeType: $mime,
|
||||||
|
fileSize: strlen($binary),
|
||||||
|
orderColumn: 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private function registerMedia(
|
private function registerMedia(
|
||||||
Model $model,
|
Model $model,
|
||||||
string $s3Key,
|
string $s3Key,
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user