HTTP Post Request with Image Javascript

3.3k Views Asked by At

I am trying to submit an Post Request to an image recognition API using Javascript, but I cannot work out how to send the actual image. I know that I cannot send it just using a local file (I get the "Cross origin requests are only supported for protocol schemes" error when I try to run it). How would I send the image using a Post request?

My code so far is:

var xhr = new XMLHttpRequest();

xhr.open("POST", "cigarette.jpg", false);
xhr.setRequestHeader("Authorization", "CloudSight [key]");

xhr.send("http://api.cloudsightapi.com/image_requests");

console.log(xhr.status);
console.log(xhr.statusText);

I am quite new to Javascript and APIs and haven't really done anything like this before; how would I send the image without going into incredibly complicated stuff?

1

There are 1 best solutions below

2
anand On BEST ANSWER

There are few issues with your code.

  1. You need correct HTTP headers to port the image.
  2. You cannot POST a JPG image like that.

Further you are not using the API properly, kindly take a look here to see how to do it.

https://cloudsight.readme.io/docs/testinput

Also find a sample here in curl

curl -i -X POST \
-H "Authorization: CloudSight [key]" \
-F "image_request[image][email protected]" \
-F "image_request[locale]=en-US" \
https://api.cloudsightapi.com/image_requests