Sending Binary Data with XMLHttpRequest

I recently had the need to send a CSV file from my add-on to a PHP server and was looking for an easier way than constructing a POST request. I discovered that XMLHttpRequest has an API for this called sendAsBinary(). Using the API on the client side was easy, but figuring out how to get the file from PHP was a little tougher, so I thought I would share the information on my blog.

Sending the data is really straightforward. I already had the CSV file in a variable. So the request looked like this:

  var xhr = new XMLHttpRequest();"POST", "");
  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');

Next was how to read the file on the server. The secret to that was reading data directly from the POST using php://input.

$postdata = file_get_contents("php://input");
$fp = fopen("file.csv", "wb");
fwrite($fp, $postdata);

And that’s it. A simple way to send binary data to a PHP server.

Please note: I reserve the right to delete comments that are offensive or off-topic.

Leave a Reply

Your email address will not be published. Required fields are marked *

4 thoughts on “Sending Binary Data with XMLHttpRequest