0

so i'm trying to upload image from ionic app to laravel web application problem it is i don't know how to do this my controller looks like this

public function postDamage(Request $request){
    try{
        $damage = new damage();
        $damage->type           =   $request->input('type');
        $damage->address        =   $request->input('address');
        $damage->description    =   $request->input('description');
        $damage->solvedBy       =   $request->input('solvedBy');
        $damage->userToken      =   $request->input('userToken');
        $damage->opstina        =   $request->input('opstina');
        $damage->image          =   $request->input('image');

        /* $imgName="";
        if ($request->hasFile('image')) {

            $imgName = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $imgName);
            $this->save();

           return back()->with('success','Image Upload successfully');
        }
        $target_path = time().'.jpg';

        $imagedata = $request->input('image');
        $imagedata = str_replace('data:image/jpeg;base64,',$imagedata);
        $imagedata = str_replace('data:image/jpg;base64,',$imagedata);
        $imagedata = str_replace(' ', '+',$imagedata);
        $imagedata = base64_decode($imagedata);
        file_put_contents($target_path,$imagedata);
        $damage->image  =   $imagedata; */

        $damage->save();
        return response()->json(['response'=>'Штетата е пратено.']);
    }catch (\Exception $e){
            return response()->json(['response'=>$e->getMessage()]);
    }

}

now how i can post some data together with image but image to be uploaded in server. The image that is generated in ionic it is in base64.

Any method i tried from google but none of them works. Thank you.

spyrox
  • 90
  • 10

1 Answers1

0

I am using Spatie Laravel Medialibrary to save images for my laravel models here is a git link: https://github.com/spatie/laravel-medialibrary

then in controller

  if ($f = $request->file) {
      $img = explode(",", $f)[1];
      $base64data = str_replace(',', '', $img); 

      $item->addMediaFromBase64($base64data)
         ->usingFileName('original.jpg')
         ->toMediaCollection('item');
    }

now in your case that might be (not tested)

     $img = explode(",", $f)[1];
     $base64data = str_replace(',', '', $img); 

     $imagedata = base64_decode($base64data);
     file_put_contents($target_path,$imagedata);
Nomi
  • 710
  • 3
  • 11
  • 21
  • Thank you for the response also and this works. Thank you again brothers. list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); file_put_contents($imgname, $data); – spyrox Mar 22 '18 at 10:38