How to send image to laravel route with AJAX

0

I have a common POST route in laravel, but in a separate project I'd like to use AJAX to send an image to this route. I'm going to use the html2canvas to get the screen screenshot.

var content = document.getElementById('welcome');

html2canvas(content, {
    onrendered: function(canvas) {
        //AQUI FICA O AJAX
    }
});

What would be the best way to do this with AJAX ??

    
asked by anonymous 20.12.2017 / 20:12

1 answer

0

You can convert canvas to image and then send it via "raw"

To convert content to image, we need to access the toDataUrl of the canvas. It will serve to turn the object into a base64 .

By default, you will receive an image in PNG , however, nothing image you can choose between JPEG or WEBP , for example.

Another thing you also need to keep in mind is that jQuery.ajax tries to convert the data to application/x-www-form-urlencoded and we do not want this. We just want to send the content of the image. For this we should mark as false , during the jQuery.ajax configuration.

Here is an example to aid understanding.

Front-end:

<h1 id="welcome">Hello Brazil!</h1>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"type="text/javascript"></script>
<script>
html2canvas( [ document.body ], {
    onrendered: function( canvas ) {
        $.ajax({
            url: 'index2.php',
            type: 'POST',
            data: canvas.toDataURL(), // Captura a imagem em base64
            contentType: 'image/png', // Informa o mime-type da imagem que por padrão é PNG
            processData: false //Informa ao jQuery.ajax para não converter os dados em application/x-www-form-urlencoded
        });
    }
});
</script>

Back-end:

As I do not know the progress of the project, I will be brief in the back end part.

First, we must capture this POST RAW . At PHP we do this by passing the php://input parameter to the file_get_contents

Then just use the str_replace function to replace the mime-type that is added when converting from canvas to base64 .

Once you've done this, you'll have your image to use in your project.

Follow the code to illustrate.

<?php

$imageEncoded = str_replace("data:image/png;base64,", "", file_get_contents("php://input"));

$imageDecoded = base64_decode($imageEncoded);

// Salva a imagem
file_put_contents("image_screenshot.png", print_r($imageDecoded, true));
    
21.12.2017 / 01:49