Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I have such code in 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. I tried to use $_POST, $_GET and $_FILES global arrays but they don’t have any files. I even tried to add file to the url like this:

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. 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”. Isn't this header necessary?

like image 751
Green Avatar asked Jan 31 '26 15:01

Green


2 Answers

Check out the post below:

image upload with ajax and php

You can't really upload a blob via the XmlHttpRequest, but you can create an AJAX like feel with hidden iframes.

It looks like there are some JQuery plugins that may help you out as well.

I hope this helps!

like image 75
marteljn Avatar answered Feb 03 '26 04:02

marteljn


Try using this for your header:

req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
like image 29
Skunkman Avatar answered Feb 03 '26 04:02

Skunkman