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(); xhr.open("POST", "http://example.com/upload.php"); xhr.overrideMimeType('text/plain; charset=x-user-defined-binary'); xhr.sendAsBinary(CSV);
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); fclose($fp);
And that’s it. A simple way to send binary data to a PHP server.