Luchezar Luchezar - 5 months ago 8
HTML Question

Saving a lot of canvas images to server

I have a script that generates about 250 images from

canvas.toDataURL()
.
My question is how to save them all at once (one request to server) instead of posting them individually.

I need a way to pack them in single request and then send them to PHP server for unpacking.

Answer

canvas.toDataURL() gives the byte data encoded in base64, they are safe to be used as strings and passed through HTTP.

do something like:

var images = [];
while(....) {
    images.push(canvas.toDataURL());
}
var imagesJson = JSON.stringify(images);
// pseudo code of jQuery ajax, you can make use of form and a hidden field 
// or any other way you'd like to query the server
$.ajax({
....
send:{images:imagesJson}
....
});

with PHP (other server side languages should almost be the same):

$images = json_decode($_POST['images'], true);
foreach($images as $image) {
    $image = base64_decode($image);
    file_put_contents('<path to file>', $image);
}