How to convert curl to ajax request

I have an HTTP API accepting a wav or mp3 file and returns a result. I am able to hit the API using the curl command curl -v -T /tmp/drawrectangle.mp3 "http://localhost:8080/client". How can i convert this into a ajax request

It looks like you want to upload file to a server and I suppose, from the browser. If yes, it could be done this way:

// given you have <input type="file" id="fileUploader"> on the page
const fileUploader = document.getElementById('fileUploader');
fileUploader.addEventListener('change', uploadFile);

const UPLOAD_URL = 'http://localhost:8080/client';

function uploadFile() {
  const [file] = this.files;
  const opts = {
    method: 'POST',
    body: file,
  };

  fetch(UPLOAD_URL, opts)
    .then(() => console.log('SUCCESS!'))
    .catch(e => console.log(e));
}

Ya i am taking the file as input but still im not able obtain the result that i get using curl

You need to give us a wee bit more to go on here: we can’t see your computer screen, we can’t see what code you’ve written, what isn’t working, what errors you’re getting, what the output you want is, what you’re doing with it. Any answers we give atm are just guessing from thousands of possible permutations of correct/incorrect ways of “making an HTTP request in a browser”

Actually i am looking transcribe my wav file using kaldi asr. The approach i used here is done using https://github.com/alumae/kaldi-gstreamer-server. i have setup this server using docker and i am trying to transcribe audio by hitting the HTTP API mentioned in the above github page and i am able to transcribe the wav using the curl command mentioned above what i am trying to achieve is to send the wav file to the server from an electron app

OK, so as said in docs, you’re sending post request with file in the body, however here you’re not uploading it (as file) but sending it as a data to be processed by server, therefore you would need to add Content-Type to the header and enable CORS on the server, so front-end app can send requests and receive responses from it.

const fileUploader = document.getElementById('fileUploader');
fileUploader.addEventListener('change', transcribeFile);

const API_URL = 'http://localhost:8888/client/dynamic/recognize';

function transcribeFile() {
  const [file] = this.files;
  const opts = {
    method: 'POST',
    body: file,
    headers: {
      'Content-Type': 'audio/wav'
    },
  };

  fetch(API_URL, opts)
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch(e => console.log(e));
}

I would guess something like this

1 Like