2012-08-15 57 views
0

我試圖將畫布保存爲圖像文件,用戶可以確定要下載哪種圖像格式(png或jpg),然後強制下載文件而無需將文件存儲在服務器上。將畫布圖像保存爲圖像文件並強制下載 - 無法打開下載對話框

這是我走到這一步:

JS腳本:

$.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"; 
     } 
    } 

的代碼不能強迫下載,我不知道爲什麼它不工作。

任何幫助非常感謝。

+0

看來該文件已被完美寫入服務器/..php/文件夾中... – 2012-08-15 12:42:04

回答

1

如果您不想將文件存儲在服務器上,則不需要以任何方式與服務器進行交互。只需讓用戶按照here所述下載畫布的內容即可。