How to send image to route from Laravel with AJAX

Asked

Viewed 221 times

0

I have a common POST route on the Laravel, but in a separate project I would like to use AJAX to send an image to that route. I will use html2canvas to get the screenshot of the screen.

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??

1 answer

0

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

To convert the content to image, we need to access the function toDataUrl canvas. It will serve to transform the object into a Base64.

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

Another that you also need to keep in mind, is that by default, the jQuery.ajax tries to convert the data to application/x-www-form-urlencoded and we don’t want that. We just want to upload the contents of the image. For that we must mark as false, during jQuery.ajax configuration.

Here is an example to help 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 don’t know the progress of the project, I will be brief in the back-end part.

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

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

Done this, you will have your image to use in your project.

Follows code to exemplify.

<?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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.