Zigomario's avatar

Upload canvas image to server

Hello,

for advance, sorry for my english very bad and my question, but i'm a young beginner in web dev. .... and also with markdown

I'm working on a meme generator plugin.
I'm fine with all but i have some problem for saving/upload image on server side.

In readme of plugin, we can see :

Saving an image on server side

You can easily send an image using AJAX request with generated image data URL as a parameter.

<a href="#" id="save">

<script type="text/javascript">
$("#save").click(function(e){
    e.preventDefault();
    
    var imageDataUrl = $("#example-save").memeGenerator("save");
    
    $.ajax({
        url: "/save-img",
        type: "POST",
        data: {image: imageDataUrl},
        dataType: "json",
        success: function(response){
            $("#preview").html(
                $("<img>").attr("src", response.filename)
            );
        }
    });
});
</script>

PHP

$data = $_POST['image'];

if(preg_match('/data:image\/(gif|jpeg|png);base64,(.*)/i', $data, $matches))
{
$imageType = $matches[1];
$imageData = base64_decode($matches[2]);

$image = imagecreatefromstring($imageData);
$filename = md5($imageData) . '.png';

if(imagepng($image, 'images/' . $filename))
{
    echo json_encode(array('filename' => '/scripts/images/' . $filename));
} else {
    throw new Exception('Could not save the file.');
}
} else {
    throw new Exception('Invalid data URL.');
}

=================================================================================

i have try lot of test, guide, tutorial... but i have always same problem === > url is no register in my table

So my question is :

how use php or ajax solution with laravel ? What should I put in my controller? my request ?

actually i use an controller like that :

public function store(MemeRequest $request, $id =null)

{

    if(!empty($id)){

        $meme_img = Images::find($id);

    }else{

        $meme_img = new Images();

    }


    $filename = "";

    if($request->hasFile('imageDataUrl')) {
        $file = $request->file('imageDataUrl');
        $filename = $file->getClientOriginalName(); // Récupère le nom original du fichier
        $destinationPath = public_path() . '/uploads/photos'; // Indique où stocker le fichier
        $file->move($destinationPath, $filename); // Déplace le fichier


        $meme_img->image = asset("uploads/photos/". $filename);

    }



    $meme_img->save();


    return Redirect::route('homepage');

}

====================================

Thank you for everything in advance

0 likes
2 replies
mehany's avatar

@Zigomario when you ask the plugin you are using to generate imageDataUrl, it looks like you submit the image data to the server as a string. So when using Laravel, it will not be different from what the plugin example shows, meaning you will be cheching for a string instead of for a file as you currently do in your controller.

Edit: maybe something like this will work

  public function store(Request $request, $id =null)
  {
      $data = $request->get('image');
  
      if (preg_match('/data:image\/(gif|jpeg|png);base64,(.*)/i', $data, $matches)) {
          $imageType = $matches[1];
          $imageData = base64_decode($matches[2]);
          $image = imagecreatefromstring($imageData);
          $filename = md5($imageData) . '.png';
  
          if (imagepng($image, public_path().'/images/' . $filename)) {
              echo json_encode(array('filename' => '/images/' . $filename));
          } else {
              throw new Exception('Could not save the file.');
          }
      } else {
          throw new Exception('Invalid data URL.');
      }
  }
1 like
Zigomario's avatar

It's beautiful :) Thanks you very much. i have all understand now.

off chance, do you know why when i use location.reload() like that _ it's broken ? :

$("#save").click(function(e){ e.preventDefault();
                    var imageDataUrl = $("#blah").memeGenerator("save");

                    $.ajax({
                            url: "/index/store",
                            type: "POST",
                            data: {image:  imageDataUrl},

                            success: function(response){
                                    $("#preview").html(
                                            $("<img>").attr("src", response.filename)
                                    );
                            }
                    });
                    location.reload();

            });
    </script>
    

=========================== i think that second fonction clear the first...but where is the solution so ?

Please or to participate in this conversation.