2

I have connected on the page welcome.blade.php javascript cropbox that truncates the image. After click on button Crop i get the string like data:image/png;base64,ivBOrwqnmdIo.........................................................................................

I write my function to send with ajax sendAvatar(img) and adding to the bottom of klick event

$('#btnCrop').on('click', function(){

    var img = cropper.getDataURL();                 
    sendAvatar(img);

})

Next i try to send to my web.php with ajax

function sendAvatar(img){ 

  var url = '{{ URL::to('getavatar') }}';
  var token = '{!! csrf_token() !!}';
    $.ajax({

       method: 'POST',
       url: url,
       data: {_token: token, img: img},
       success: function(){
       alert(img);
      }


   });

}

I have a model Avatar.php with field avatar_url

class Avatar extends Model
 {
   protected $fillable=['id','avatar_url'];
 }

Now i try in my web.php store the image in my db

But i don t know how to do this. Please help me

I am use laravel 5.4

Ramzan Mahmood
  • 1,881
  • 2
  • 21
  • 46

3 Answers3

1

In my case i used this approach

In my web.php

Route::post('/getavatar', 'AvatarController@saveAvatar');

In my AvatarController

use App\Avatar;
use Auth;

class AvatarController extends Controller
{
   public function saveAvatar(Request $request)
    {
       $data = $request->get('img');

       list($type, $data)  = explode(';', $data);
       list(, $data)       = explode(',', $data);
       $data               = base64_decode($data);
       $avatar_owner       = Auth::user()->id;

      $avatarName          = rand(000000000, 999999999) . '-' .         $avatar_owner .'.png';
      $avatar_uri          = file_put_contents(public_path() . '/images/' . $avatarName, $data);


       $avatar = new Avatar();
       $avatar->avatar_url = $avatarName;

       $avatar->save(); 

}

}

0

The img field that you send to server is in string format and encoded as base64. you should convert base64 string to binary format via some php code like this; then store binary file and then put the path of the binary file in database.

Community
  • 1
  • 1
Amin Fazlali
  • 1,209
  • 1
  • 9
  • 17
0

cropper.getDataURL(); <-- this returns base_64 data so you need to store this data into file using php

here is php code sample how to do this

do this in your controller and store $logoName in your database

    $logoName = null;

    if( isset($_POST['imagebase64']) and strlen($_POST['imagebase64']) > 700 )
    {
        $data               = $_POST['imagebase64'];
        list($type, $data)  = explode(';', $data);
        list(, $data)       = explode(',', $data);
        $data               = base64_decode($data);
        $logoName           = rand(000000000, 999999999) . '.png';
        file_put_contents(public_path() . '/some_path/' . $logoName, $data);

    }
Anri
  • 1,706
  • 2
  • 17
  • 36