POST XMLHTTPRequest 中的 base64 png

POST base64 png in XMLHTTP Request

出于某种原因,此信息无法找到直接的答案,我已经尝试解决了一个多星期。所以请只给一个有用的答案!

我正在通过以下步骤将 canvas.toDataUrl 图像保存到服务器中:

JAVASCRIPT

function captureCanvas(){
    html2canvas(displayScreen).then(canvas =>{
        postPicture(canvas.toDataURL());
    })
}

function postPicture(data){
    let xhr = new XMLHttpRequest();
    xhr.onload = function (){
        if (this.status == 200){
         let result = document.getElementById('result-pic');   
         console.log('this is the response:'+this.response);
         result.src = this.response;
        }
    }
    xhr.open('POST', 'storeImage.php', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send('image='+data);
}

然后尝试将其存储在服务器端/将结果显示回 html 文件: PHP

$baseFromJavascript = $_POST['image'];
$data = base64_decode(preg_replace('#^data:image/w+;base64,#i', '', $baseFromJavascript));
$filepath = "./upload/image.png";
file_put_contents($filepath,$data);

echo $baseFromJavascript;

它既没有在本地作为图像打开也没有显示到 html,即使 html imgbase64 数据.

您必须对 Javascript 以及 PHP

进行一些更改

在 JS 中对您的数据进行编码,以便正确发送请求

function captureCanvas(){
    html2canvas(displayScreen).then(canvas =>{
        postPicture(canvas.toDataURL());
    })
}

function postPicture(data){
    let xhr = new XMLHttpRequest();
    xhr.onload = function (){
        if (this.status == 200){
         let result = document.getElementById('result-pic');   
         console.log('this is the response:'+this.response);
         result.src = this.response;
        }
    }
    xhr.open('POST', 'storeImage.php', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send('image='+encodeURIComponent(data));
}

如下更改您的 php 脚本:

$baseFromJavascript = $_POST['image'];
$data = $baseFromJavascript;
list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
$filepath = "./upload/image.png";
file_put_contents($filepath,$data);

echo $baseFromJavascript;