Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert image to base 64 string with Laravel

I want to convert an image to base 64 with Laravel. I get the image from a form . I tried this in my controller:

public function newEvent(Request $request){
    $parametre =$request->all();

    if ($request->hasFile('image')) {
        if($request->file('image')->isValid()) {
            try {
                $file = $request->file('image');
                $image = base64_encode($file);
                echo $image;


            } catch (FileNotFoundException $e) {
                echo "catch";

            }
        }
    }

I get this only:

L3RtcC9waHBya0NqQlQ=

like image 367
Pondikpa Tchabao Avatar asked Sep 13 '17 21:09

Pondikpa Tchabao


2 Answers

Laravel's $request->file() doesn't return the actual file content. It returns an instance of the UploadedFile-class.

You need to load the actual file to be able to convert it:

$image = base64_encode(file_get_contents($request->file('image')->pat‌​h()));
like image 113
M. Eriksson Avatar answered Oct 22 '22 13:10

M. Eriksson


It worked for me in the following way:

$image = base64_encode(file_get_contents($request->file('image')));

I eliminated this part ->pat‌​h();

like image 32
C47 Avatar answered Oct 22 '22 12:10

C47