Search code examples
laravel-livewirelaravel-medialibrary

How in livewire 2 app upload image in laravel-medialibrary?


In Laravel 8 / livewire 2 app I added spatie/laravel-medialibrary 9, when a preview of selected I make with methods

    <input type="file" id="image" wire:change="$emit('fileChosen')">
    ... 

    Livewire.on('fileChosen', app_image_id => {
        alert('fileChosen' + app_image_id);
        let inputField = document.getElementById('image')
        let file = inputField.files[0]
        console.log('file::')
        console.log(file)
        let file_name = file.name

        // console.log('file_name::')
        // console.log(file_name)

        let reader = new FileReader()
        console.log('reader::')
        console.log(reader)
        //
        reader.onloadend = () => {
            window.livewire.emit('fileUpload', reader.result, file_name)
            // console.log('reader.result::')
            // console.log(reader.result)
        }
        reader.readAsDataURL(file)    
   })

   public function handleFileUpload($imageData, $file_name)
   {
       $this->uploaded_file_name = $file_name;
       $this->uploadedAppImageImage  = $imageData;
   }

as result in uploadedAppImageImage I have content of the uploaded file which looks like a long string :

File `data:image/png;base64,iVBORw0KGg c TC4u3U1VaLKoOgg...mCC` AAAAElFTkSuQmCC` does not exists

But looking at laravel-medialibrary methods for image adding https://spatie.be/docs/laravel-medialibrary/v9/api/adding-files#addmediafromdisk I do not see which method can I to use image content in $uploadedAppImageImage ?

UPDATED PART # 1: I found method addMediaFromString (https://spatie.be/docs/laravel-medialibrary/v9/api/adding-files#addmediafromstring) :

But making some tests with i see that uploaded image is invalid. I try to decode from base64(I wrote above how content of file looks like). I tried several methods, like :

  ->addMediaFromString( base64_decode( str_replace(' ','+',$this->uploadedAppImageImage)) )

  ->addMediaFromString( base64url_decode($this->uploadedAppImageImage) )

Last method is written here https://www.php.net/manual/ru/function.base64-decode.php as :

function base64url_decode($data) {
    return base64_decode(str_replace(array('-', '_'), array('+', '/'), $data));
}

but anyway uploaded image is invalid. Which method have I to try ?

Thanks!


Solution

  • I found this code :

            list($type, $data) = explode(';', $data);
            list(, $data)      = explode(',', $data);
            $data = base64_decode($data);
    

    made valid converting into image!