web_ninja
web_ninja

Reputation: 2401

How to save a wav file on the server in PHP if it has been sent using XMLHttpRequest?

I am using the following snippet to send a wav file as a blob to the server which is written in PHP:

function upload(blob) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload.php', true);
    xhr.onload = function (e) {
        var result = e.target.result;
    };

    xhr.send(blob);
}

I am confused as to how I should handle the POST data on the server.

Upvotes: 0

Views: 1232

Answers (2)

geocar
geocar

Reputation: 9295

What you're looking for is php://input:

$fp = fopen("php://input", "r");
$wav_file = stream_get_contents($fp);

Note that I'm assuming blob in your example is an actual Blob, or ArrayBuffer, or File, and not just a bunch of text whose UTF8 interpretation is also a valid WAVE file.

Upvotes: 1

Jelle Keizer
Jelle Keizer

Reputation: 721

<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />



<script>
   var client = new XMLHttpRequest();

   function upload() 
   {
      var file = document.getElementById("uploadfile");

      /* Create a FormData instance */
      var formData = new FormData();
      /* Add the file */ 
      formData.append("upload", file.files[0]);

      client.open("post", "/upload", true);
      client.setRequestHeader("Content-Type", "multipart/form-data");
      client.send(formData);  /* Send to server */ 
   }

   /* Check the response status */  
   client.onreadystatechange = function() 
   {
      if (client.readyState == 4 && client.status == 200) 
      {
         alert(client.statusText);
      }
   }
</script>

Upvotes: 0

Related Questions