Skip to content

Instantly share code, notes, and snippets.

@eduPHP
Created March 29, 2021 18:14
Show Gist options
  • Select an option

  • Save eduPHP/e344bda5c0b7bb19c13468791853cb55 to your computer and use it in GitHub Desktop.

Select an option

Save eduPHP/e344bda5c0b7bb19c13468791853cb55 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class ImageUploadsFormRequest extends FormRequest
{
protected function prepareForValidation()
{
$input = $this->all();
if (!isset($input['image'])) {
return;
}
if (Str::startsWith($input['image'], 'data:image')) {
$file = $this->makeFromBase64($input['image']);
$input['image'] = $file;
}
$this->replace($input);
}
protected function makeFromBase64($content)
{
$content = Arr::last(explode(',', $content));
$content = base64_decode($content);
$mimeType = finfo_buffer(finfo_open(), $content, FILEINFO_MIME_TYPE);
$extension = finfo_buffer(finfo_open(), $content, FILEINFO_EXTENSION);
$size = strlen($content);
$name = uniqid('img_') . '.' . $extension;
$path = tempnam(sys_get_temp_dir(), uniqid('img-', true));
File::put($path, $content);
return app(UploadedFile::class, [
'path' => $path,
'originalName' => $name,
'mimeType' => $mimeType,
'size' => $size,
'error' => null,
'test' => true,
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment