2015-10-14 54 views
1

我想提交一个发布请求到图像识别API使用Javascript,但我不能解决如何发送实际图像。我知道我不能仅仅使用本地文件发送它(当我尝试运行它时,我得到了“跨源请求仅支持协议方案”错误)。我如何使用Post请求发送图像?HTTP Post请求与图像Javascript

到目前为止我的代码是:

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);

我很新的Javascript和API和以前真的没有做过这样的事;我怎么会发送图像,而不会进入令人难以置信的复杂的东西?

+0

这取决于什么格式的服务期望的数据是(我不知道那个,似乎是因为他们不” t似乎与[他们的API主页](http://cloudsightapi.com/api)中的任何面向公众的文档链接)。哦,不,找到了文档,他们只是隐藏在页面中间的链接(看起来不像链接)。 – Quentin

+1

(open的第二个参数应该是web服务端点的URL)。 – Quentin

+0

因此[它说](https://cloudsight.readme.io/)“图像作为多部分形式请求部分附加。”,这意味着您只需以常规方式发布表单数据。 – Quentin

回答

0

您的代码很少出现问题。

  1. 您需要正确的HTTP头来移植图像。
  2. 你不能发布这样的JPG图像。

此外,您没有正确使用API​​,请看看这里看看如何去做。

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

此外,在这里找到一个样本卷曲

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 
+0

谢谢,我将:当你说正确的HTTP头来移植图像,你是什么意思? – teamshortcut

+0

你需要设置一个HTTP Header'Authorization:CloudSight [key]'和'multipart/form-data',这是常规'xhr'无法做到的。你可能想切换到jQuery以更好的方式来做到这一点。 – anand