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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top