本文介紹了xhr 發(fā)送 base64 字符串并在服務(wù)器中將其解碼為文件的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試將 base64 編碼的 img 發(fā)送到服務(wù)器,javascript 看起來像
I am trying to to send a base64 encoded img to server,the javascript looks like
var xhr=new XMLHttpRequest()
var reader=new FileReader()
reader.onloadend=function(e){
xhr.onload=function(e){
alert(xhr.responseText)
}
xhr.open("POST","upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//xhr.setRequestHeader("X-File-Name", file.name);
//xhr.setRequestHeader("X-File-Type",file.type)
xhr.send(e.target.result)
}
reader.readAsDataURL(file)
},false)
在 php 中,如下所示:
In php,looks like this:
echo "some response Text";
$postdata = file_get_contents("php://input");
file_put_contents('MyFile.jpg', base64_decode($postdata));
最后,服務(wù)器得到一個(gè)文件正好與發(fā)送的文件一樣大,但是無法打開
有人有一些想法嗎?非常感謝!
And,eventually,the server gets a file exactly as big as the sent file,However,it can't be opened
Some one get some ideas?Thanks a lot!
推薦答案
reader.readAsDataURL(file)
數(shù)據(jù) URL 與文件的 base64 版本不同.你會(huì)得到額外的垃圾.它看起來像這樣:
A data URL is NOT the same as a base64 version of the file. You get extra garbage in it. It looks like this:
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
參見維基百科.
嘗試對(duì)其做一個(gè)簡單的正則表達(dá)式:
Try doing a simple regex on it:
var data = dataURL.match(/,(.*)$/)[1];
或者,在您的代碼中,
xhr.send(e.target.result.match(/,(.*)$/)[1]);
這篇關(guān)于xhr 發(fā)送 base64 字符串并在服務(wù)器中將其解碼為文件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!