Question

I'm trying to save canvas as a image file ,users get to determine which image format to download (png or jpg), then force download the file without storing the file on the server.

This is what I got so far:

JS Script:

$.ajax(
{
type : "POST",
    url : "../php/download_image.php",
data:
    {
    format: 'png',
    dataURL: flattenCanvas.toDataURL('image/png')
    }
});

PHP:

    $data = $_POST['dataURL'];
    $format = $_POST['format'];
    $file = $file = md5(uniqid()) . '.'.$format;
    $uri =  substr($data,strpos($data,",")+1);
    file_put_contents($file, base64_decode($uri));

    if($format == 'png')
    {
        if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: image/png');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
        }
        else {
        echo "$file not found";
        }
    }

The code cannot force download and I have no idea why it is not working.

Any help greatly appreciated.

Was it helpful?

Solution

If you don't want to store the file on the server, you don't need to interact with the server in any way. Just let the user download the content of the canvas as described here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top