XHR发送的base64字符串和DE code将其在服务器上的文件 [英] xhr send base64 string and decode it in the server to a file

查看:190
本文介绍了XHR发送的base64字符串和DE code将其在服务器上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图发送一个base64连接codeD IMG服务器,javascript的样子

  VAR XHR =新XMLHtt prequest()
VAR读卡器=新的FileReader()
reader.onloadend =功能(E){
xhr.onload =功能(E){
警报(xhr.responseText)
}
xhr.open(POST,upload.php的);
        xhr.setRequestHeader(缓存控制,无缓存);
        xhr.setRequestHeader(X-要求,用,XMLHtt prequest);
        //xhr.setRequestHeader(\"X-File-Name,file.name);
        //xhr.setRequestHeader(\"X-File-Type\",file.type)
xhr.send(e.target.result)
}
reader.readAsDataURL(文件)
},假)



在PHP中,看起来像这样:

 回声一些回应文本;
$ POSTDATA =的file_get_contents(PHP://输入);
的file_put_contents('MyFile.jpg',base64_de code($ POSTDATA));

和,最终,服务器得到一个文件的究竟大如发送的文件,但是,它不能打开

有人得到一些想法?非常感谢!


解决方案

  reader.readAsDataURL(文件)

一个数据URL是不一样的文件的一个base64版本。你在这额外的垃圾。它看起来是这样的:

 数据:[< MIME类型>] [;字符集=<&编码GT;] [; BASE64]<数据>

请参阅维基百科

尝试在它做一个简单的正则表达式:

  VAR数据= dataURL.match(/(*)$ /)[1];

或者,在code,

  xhr.send(e.target.result.match(/(*)$ /)[1]);


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!

解决方案

reader.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]);

这篇关于XHR发送的base64字符串和DE code将其在服务器上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆