[英]How to receive data, sent from the browser using XMLHttpRequest, in server-side (php)?
I cannot understand how to get blobs from XMLHttpRequest in my PHP script. 我无法理解如何在我的PHP脚本中从XMLHttpRequest获取blob。 I have such code in JS: 我在JS中有这样的代码:
var req = new XMLHttpRequest(); // create instance
var file = document.getElementById('file').files[0]; // get File Object from <input type=file />. It is picture
req.open("POST", “uploader.php”, true); // make request
req.setRequestHeader("Content-Type", file.type); set request headers
req.setRequestHeader("Content-Length", file.size);
req.send(file); // send request with file-blob
if (req.readyState == 4 && req.status == 200) {
alert("result = " + req.responseText);
}
I understand how to send the blob to the server, but don't understand how and from where to get it there. 我理解如何将blob发送到服务器,但不了解如何以及从何处获取它。 I tried to use $_POST
, $_GET
and $_FILES
global arrays but they don't have any files. 我尝试使用$_POST
, $_GET
和$_FILES
全局数组,但它们没有任何文件。 I even tried to add file
to the url like this: 我甚至试图将file
添加到网址中,如下所示:
req.open("POST", “uploader.php?file=” + file, true);
It's not the solution either. 它也不是解决方案。
Reading answers here I found that I can get raw binary data using php://input
. 在这里阅读答案我发现我可以使用php://input
获取原始二进制数据。 I tried and yes I got some raw data. 我试过,是的,我得到了一些原始数据。 Going to examine this solution through and through. 要彻底检查这个解决方案。 But want to ask is this the only way? 但想问这是唯一的方法吗? If not, what are the others? 如果没有,其他人是什么? And which one is the most right then? 哪一个是最正确的呢?
Also, when I set header ("Content-Length", file.size)
the console.log
shows error and says “Refused to set unsafe header “Content-Length”. 此外,当我设置标题("Content-Length", file.size)
, console.log
显示错误并显示“拒绝设置不安全标题”Content-Length“。 Isn't this header necessary? 这个标题不是必需的吗?
Check out the post below: 看看下面的帖子:
image upload with ajax and php 使用ajax和php上传图片
You can't really upload a blob via the XmlHttpRequest, but you can create an AJAX like feel with hidden iframes. 您无法通过XmlHttpRequest真正上传blob,但您可以使用隐藏的iframe创建类似AJAX的感觉。
It looks like there are some JQuery plugins that may help you out as well. 看起来有一些JQuery插件也可以帮助你。
I hope this helps! 我希望这有帮助!
尝试将此用作标题:
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.