3

To everyone who mask this as a duplicate; please see the other answers you are refering to and the links I have provided here. They content type is audio/wav and not stream/octet as mentioned in other answers. Please don't mark questions as duplicates without reading its content

I am trying to send an audio file to a server, so I can get an JSON response back. This is an IBM Service so we have the REST API provided by them. Below is my code in ajax

function recognize()
            {
                $.ajax
                ({
                    type: "POST",
                    url: "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize",
                    dataType: 'json',
                    username: "xxxx",
                    password: "xxxx",
                    contentType: "audio/wav",


                    success: function (data){
                        alert(JSON.stringify(data)); 
                    }
                });
            }

Below is the IBM example for the REST call I am going to make -

curl -u "{username}":"{password}" \
-H "content-type: audio/wav" \
--data-binary @"/path/to/file.wav" \
"https://stream.watsonplatform.net/speech-to-text/api/v1/sessions/{session_id}/recognize"

The link to the example page and description is - http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/speech-to-text/api/v1/#recognize

My question is, how Can I send the binary file via Ajax? This is actually a phonegap application.

Here is an interesting question; if I send the URI of the file into data: tag of the REST call it works. If I send the real path it do not. why???

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • Possible duplicate of [Sending binary data in javascript over HTTP](http://stackoverflow.com/questions/19959072/sending-binary-data-in-javascript-over-http) – Mark Feb 25 '16 at 17:50
  • @Mark: See the edit I made. – PeakGen Feb 25 '16 at 17:58
  • Did you try the method in the other question? If so, you should add that information to your question and also any errors about why it didn't work. If you haven't tried it, please do so. Binary data should be binary data regardless of the content-type. – Mark Feb 25 '16 at 18:02

1 Answers1

2

You can use XMLHttpRequest to send binary data

ar oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
  // Uploaded.
};

var blob = new Blob(['abc123'], {type: 'audio/wav'});

oReq.send(blob);
Filix Mogilevsky
  • 727
  • 8
  • 13