Home > Blockchain >  Laravel how to save the base64 data image?
Laravel how to save the base64 data image?

Time:03-14

I know how to save a normal file from HTML <form> with type="file"

maybe I can do that $request->file('avatar')->store('avatars');

Actually, I using a Js package about a image upload & drop & crop

HTML / Blade

<form action="{{route('avatar.update')}}" method="POST" enctype="multipart/form-data" id="avatar">
<div 
      data-label="Select your Avatar"
      data-size="400,400"
      data-ratio="1:1">
    <input type="file" name="avatar" >
</div>
<button type="submit"> Update </button>
</form>

when the form submit with selected a image.

$request->file('avatar') = null

Because I check when the submit, the input('avatar') will be changed to type="hidden", so I can use $request->file('avatar')

Then.... dd($request->all()); I got



[
  "_token" => "od91HbEuWSbgx5gqfaNOeHQIC8qUBMumzf7u4Dvr",
  "avatar" => "{
      "server":null,
      "meta":{},
    
      "input":{"name":"ccc.png","type":"image/png","size":1412200,"width":2860,"height":1440,"field":null},
    
      "output":{"name":"ccc.png",
                "type":"image/png",
                "width":400,"height":400,
                "image":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUCC....etc"},
      
      "actions":{"rotation":null,"crop":{"x":710,"y":0,"height":1440,"width":1440,"type":"auto"},"size":{"width":400,"height":400},"filters":{"sharpen":0},"minSize":{"width":0,"height":0}}
    
    }"
]

I get this image is base64 format? how can I to save it?

I try base64_decode but not work. $avatar = base64_decode($request->input('avatar'));

fixed the problem from @gguney!

the main problem is I forgot to json_decode the avatar input!

controller code now


        $image = json_decode($request->input('avatar'))->output->image;
        $imageName = time() . 'ava.png';

        $image = str_replace('data:image/png;base64,', '', $image);
        $image = str_replace(' ', ' ', $image);
        Storage::disk('temp_avatar')->put($imageName, base64_decode($image));

CodePudding user response:

This should work:

json_decode($request->input('avatar'))->output->image
  • Related