Jason Liao
Jason Liao

Reputation: 11

Save canvas image as image file and force download - fail to open download dialog

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.

Upvotes: 0

Views: 2305

Answers (1)

matthias.p
matthias.p

Reputation: 1544

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.

Upvotes: 1

Related Questions