admin管理员组文章数量:1237563
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)
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!
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)
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!
- 1 Open them up with a hex editor and see if there's anything obvious wrong. – TheCodeKing Commented Sep 11, 2011 at 1:00
1 Answer
Reset to default 18reader.readAsDataURL(file)
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>
See Wikipedia.
Try doing a simple regex on it:
var data = dataURL.match(/,(.*)$/)[1];
Or, in your code,
xhr.send(e.target.result.match(/,(.*)$/)[1]);
本文标签: javascriptxhr send base64 string and decode it in the server to a fileStack Overflow
版权声明:本文标题:javascript - xhr send base64 string and decode it in the server to a file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739482105a2165189.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论