How to upload file with livewire?

How to upload file with livewire ?

I don’t want to reinvent the wheel, so I’m also desperately waiting for @calebporzio to show his “Project L”. Here file uploads are present: twitter.

Does this help you?

Yes it is possible to upload file using Livewire. But you must also leverage javascript for passing base64 file data into livewire component.

I have found a tutorial on multiple files upload here.

A short snippet here
You file upload blade template.

<input type="file" class="form-control" wire:change="$emit('single_file_choosed')" >;
@if($image)
   <img src="{{ $image }}" alt="" style="height: 150px;" class="img-thumbnail" >
@endif

File Component

<?php

namespace App\Http\Livewire\Files;

use Exception;
use Livewire\Component;
use Log;
use File;
use Illuminate\Support\Str;
use Storage;
use Illuminate\Support\Facades\Validator;

class FileUpload extends Component
{

    public $image;

    public $files = [];

    public $listeners = [
        "single_file_uploaded" => 'singleFileUploaded',
    ];


    public function singleFileUploaded($file){

        try {
            if($this->getFileInfo($file)["file_type"] == "image"){
                $this->image = $file;
            }else{
                session()->flash("error", "Uploaded file must be an image");
            }
        } catch (Exception $ex) {
            
        }
    }

    public function getFileInfo($file){
        $info = [
            "decoded_file" => NULL,
            "file_meta" => NULL,
            "file_mime_type" => NULL,
            "file_type" => NULL,
            "file_extension" => NULL,
        ];
        try{
            $info['decoded_file'] = base64_decode(substr($file, strpos($file, ',') + 1));
            $info['file_meta'] = explode(';', $file)[0];
            $info['file_mime_type'] = explode(':', $info['file_meta'])[1];
            $info['file_type'] = explode('/', $info['file_mime_type'])[0];
            $info['file_extension'] = explode('/', $info['file_mime_type'])[1];
        }catch(Exception $ex){

        }

        return $info;
    }

}

Javascript to get base64 of image and emit the component event

 window.livewire.on('single_file_choosed', function(){
    
 try {
    
    let file = event.target.files[0];
             

    if(file){
                      
            let reader = new FileReader();

             reader.onloadend = () => {
                window.livewire.emit('single_file_uploaded', reader.result);
            }
            reader.readAsDataURL(file);
        }
    } catch (error) {
        console.log(error);
    }

});