本文介紹了xhr 發送 base64 字符串并在服務器中將其解碼為文件的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試將 base64 編碼的 img 發送到服務器,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));
最后,服務器得到一個文件正好與發送的文件一樣大,但是無法打開
有人有一些想法嗎?非常感謝!
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)
數據 URL 與文件的 base64 版本不同.你會得到額外的垃圾.它看起來像這樣:
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>
參見維基百科.
嘗試對其做一個簡單的正則表達式:
Try doing a simple regex on it:
var data = dataURL.match(/,(.*)$/)[1];
或者,在您的代碼中,
xhr.send(e.target.result.match(/,(.*)$/)[1]);
這篇關于xhr 發送 base64 字符串并在服務器中將其解碼為文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!