我正在尝试将 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 字符串并在服务器中将其解码为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!