xhr send base64 string and decode it in the server to a file(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 字符串并在服务器中将其解码为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:xhr 发送 base64 字符串并在服务器中将其解码为文件


基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01