2016-02-29 97 views
1

我想通過ajax發送base64轉換圖像到PHP後端。我使用encodeURIComponent來編碼base64圖像,還必須使用encodeURI來編碼參數。否則,它不斷給我403拒絕訪問錯誤。當我發送像這樣的形象變得腐敗的形象。當我只使用encodeURIComponent來編碼圖像。和發送,而不使用是encodeURI它完美編碼參數。(僅在本地服務器。)Base64圖像通過Ajax encodeURIComponent發送

下面的代碼只能在本地服務器(WAMP)的作品

   var img = canvas.toDataURL("image/png"); 

       var Parameters = "image=" + encodeURIComponent(img) + "&filename=" + name; 

       $.ajax({ 
        type: "POST", 
        url: "savePNG.php", 
        data: Parameters, 
        success: function (response) { 
         alert(response); 
        } 
       }); 

當我再次它編碼data: encodeURI(Parameters),將數據解析到後端。但圖像會變壞(我認爲是因爲它編碼了兩次)。

PHP後端代碼如下所示。

$image = $_POST['image']; 

$filename = $_POST['filename']; 

$image = str_replace('data:image/png;base64,', '', $image); 
$decoded = base64_decode($image); 

file_put_contents($filename . ".png", $decoded, LOCK_EX); 

echo $image; 

有沒有辦法在服務器上工作,沒有圖像變壞。

回答

2

使用以下技巧。

的JavaScript

var img = canvas.toDataURL("image/png"); 

var ajax = new XMLHttpRequest(); 
ajax.open("POST", 'savePNG.php', false); 
ajax.setRequestHeader('Content-Type', 'application/upload'); 
ajax.send(img); 

PHP代碼

$imageData=$GLOBALS['HTTP_RAW_POST_DATA']; 
$filteredData=substr($imageData, strpos($imageData, ",")+1); 
$unencodedData=base64_decode($filteredData); 
$fp = fopen("filename.png", 'wb'); 
fwrite($fp, $unencodedData); 
fclose($fp); 
+0

謝謝你的男人。你的代碼幫助我解決了我的問題。 – Rajkeshar