PHP: Make capture with html2canvas.js and save it to a server

0

I see that with this library we can print the resulting image somewhere in the DOM or even download it.

What I need to save it on a server with php using ajax. In the following way I could store the img to pass it later by ajax.

var data = drawingCanvas.toDataURL('image/png');

What should I do in said php to achieve it?

Thank you very much!

    
asked by Adrià Fàbrega 14.06.2018 в 23:54
source

1 answer

0

Javascript

var data = {
    image : drawingCanvas.toDataURL('image/png') 
}

$.ajax({
    url: 'url del PHP',
    type: "POST",
    dataType: 'json',
    data: data,
    success: function(obj) {
        console.log(obj);
    },
    error: function(xhr, textStatus, errorThrown) {
        console.error(xhr);
    }
});

PHP

// crea la carpeta en caso de que no exista y le asigna permisos
function create_folder($path=false){
    if ($path && !file_exists($path))
        mkdir($path, 0777);
}

// convierte base64 enviado por ajax en archivo
function base64ToImage($folder , $data, $fileName = null){
    if(strlen($data)<3){
        return false;
    }

    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);
    $folder = "{$_SERVER['DOCUMENT_ROOT']}/{$folder}/";

    create_folder($folder);

    if(!$fileName) $fileName = md5($data);
    $imgFile = "{$folder}/{$fileName}";

    if (file_exists($imgFile)) {
        unlink($imgFile);
    }

    if(!file_put_contents($imgFile, $data)){
        return false;
    }

    return $imgFile;
}

base64ToImage('documentos', $_POST['image'], 'imagen.png');
    
answered by 15.06.2018 в 00:52