Implementing Microsoft's Project Oxford - Emotion API and file upload - javascript

I'm looking to be able to implement the Emotion API from Project Oxford on my website. I've currently written the below HTML/JavaScript code which checks an image from a URL and displays the result of said image after having run the Emotion API:
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
// Request body
data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
//console.log(data);
//alert(data.scores);
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
This code works fine, however I'm looking to implement this on my website such that people upload images themselves locally from their machine with the use of a browse button as opposed to looking up an image using the link. Any help would be very much appreciated!

I mocked this up using application/octet-stream as the body type which allows you to post a binary object (i.e. the image itself), rather than a url to an image. The Emotion API documentation details how this is a supported content type.
I've continued with use of JQuery as per your original example.
You should be able to copy and paste this entire example into a HTML file, add your Emotion API key where it says my-key and it will work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" name="filename">
<button id="btn">Click here</button>
<script type="text/javascript">
$('#btn').click(function () {
var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: file,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
alert(error.getAllResponseHeaders());
});
});
</script>
</body>
</html>

Related

How to receive judgement result from model of Custom Vision with JavaScript

I want to receive judgement result from model of Azure Custom Vision by using JavaScript.
I changed JavaScript code that this site has.
https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814
But I can't.
What is wrong with my code?
I changed IterationId, application, url, content-Type, Prediction-key, and data.
These part are enclosed with {} in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Human</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"iterationId": "{Iteration id that showed in Performance Page}",
"application": "{My Project name of Custom Vision}",
};
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Of course, I expected showing "success".
But, the actual output is "error"......
When I changed URL that this site has(https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814) in my code, I can get Success message.
And, I also write
processData: false,
contentType: false,
in ajax in my code
Change your code to see what is the error that you get back:
(Note the new "error" parameter to the request)
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
error: function(xhr,status,error) {
// >>>>>>>>>>>> CHECK HERE THE ERROR <<<<<<<<<<<<
}
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
Once you have the error, it would be easier to help you.

Uploading a file with JavaScript/Ajax to SpringBoot endpoint

I am new to front-end development and am having troubles piecing together a solution for this specific form setup.
I have an already created jsp representing this instance creation page. It's a form containing numerous drop downs and check boxes. I need to add a file upload option to it.
The jsp is set up like this...
<form class="form-horizontal" id="editInstanceForm" onsubmit="return false;"> ....
Here's my input field
<div class="form-group" id="uploadForm">
<label class="col-xs-4 control-label instanceDefaultLabel" for="fileSearchField">Default Location and Zoom:</label>
<div class="col-xs-3">
<input name="myFile" type="file" id="fileSearchField" multiple=false>
<button id="upload-button">Upload</button>
</div>
.....
</div>
Now I have an ajax call that I was originally wanting to use before I realized that the whole form is attempting to submit when I uploaded the file. Here it is...
$('#upload-button').click( 'click',
function() {
var form = $('#fileSearchField')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/edit/uploadfile",
data: data,
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert("hi stuff worked");
},
error: function (e) {
alert("nope!");
}
});
}
);
I got this suggestion in researching how to upload a file with jQuery/ajax and Spring Boot (I am using Spring Boot to create my endpoint). Here are some articles that I have been reading in an attempt to understand how to do this...
https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/
http://javasampleapproach.com/spring-framework/spring-boot/multipartfile-create-spring-ajax-multipartfile-application-downloadupload-files-springboot-jquery-ajax-bootstrap#3_Implement_upload_controller
and many more. This seemed like the solution until I realized this was a form and I think I need to save all the fields at once. This is going to mean that I have to modify the already created ajax function that saves this form and passes it to the end point. Now I don't know how to get my MulitpartFile in as part of this different function. The existing one is like this...
$.ajax({
type: "POST",
url: webroot + "/viewerConfig/mapInstance/insertOrUpdate",
data: JSON.stringify(instanceData),
processData: false,
contentType: 'application/json',
success: function (data) {
if (data.status === "OK") {
alert("Instance created/updated successfully");
} else {
alert("Unknown error");
}
},
fail: function () {
alert("Unknown error");
},
error: function (a) {
alert("Unknown error");
}
});
});
This is exactly where I am stuck and I need to be pointed in the correct and productive direction.
I don't know if this will help but here's my end point that looks like the one I have to hit with my file param added...
#RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody BaseStatusResponse insertOrUpdate(final #RequestBody SaveAdminInstanceView newInstance, HttpServletResponse servletResponse,
#RequestParam MultipartFile file)
EDIT:
I have done some curl troubleshooting and it's the MulitpartFile that's failing. I am passing it as suggested yet I am getting this exception:
org.springframework.web.multipart.MultipartException: The current request is not a multipart request</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
You can try below code:
$.ajax({
url: "/edit/uploadfile",
type: 'POST',
data: new FormData($(this)[0]),
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
cache: false,
success: function(res) {
console.log(res);
},
error: function(res) {
console.log('ERR: ' + res);
}
});
And in controller, you needn't declare consumes = "application/json"
I figured out what I was doing wrong. It wants the form element not the file one. FormData needs the Form. Thanks for your help though! :)
There you have 3 diferent ways to do this with spring-boot at 2022 be sure the file size is lower than the server maximun file size.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="http://192.168.12.168:8081/uploadfile" enctype="multipart/form-data">
<input type="file" id="fileinput" name="file" /><br/><br/>
<input type="submit" value="Submit using HTML" />
</form>
<button onclick="submitStyle1()">Submit using FETCH</button>
<button onclick="submitStyle2()">Submit using XHR</button>
</body>
<script>
function submitStyle1(){
const photo = document.getElementById("fileinput").files[0];
const formData = new FormData();
formData.append("file", photo);
fetch('http://192.168.12.168:8081/uploadfile', {method: "POST", body: formData});
}
function submitStyle2(){
const photo = document.getElementById("fileinput").files[0]; // file from input
const req = new XMLHttpRequest();
const formData = new FormData();
formData.append("file", photo);
req.open("POST", 'http://192.168.12.168:8081/uploadfile');
req.send(formData);
}
</script>
</html>
To see an example type me at https://github.com/JmJDrWrk

U.N. FAO API - How do I do a POST data request via JS with this API?

I am trying to do a POST request (via JavaScript AJAX) to the United Nations Food and Agriculture Organization (U.N. FAO) API to get some data points. While I have successfully completed GET requests to this API with no problem, the POST requests continuously fail. I've done this type of request with many other APIs, but this one I can't figure out.
My code and URLs related to the API are below.
Can anyone please help me successfully complete a POST data request to this FAO API? Either modifying my code or creating your own example code would be fine.
The API endpoint is here:
http://fenixapps2.fao.org/api/v1.0/en/data/
The API's technical description is here:
http://fenixapps2.fao.org/api/v1.0/
The 'Example Page' for the API is here:
http://faostat.github.io/faostat-api/
The 'Showcase Page' for the API is here:
http://fenixapps.fao.org/repository/api/
My code -- a working GET request + non-working POST request -- is below.
You can cut-and-paste it into a text editor and it will work as an HTML file.
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascript'>
function test() {
// (1) GET requests work fine.
// Based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
$.ajax({
type: 'GET',
url: 'http://fenixapps2.fao.org/api/v1.0/en/classifications/QC',
success: function(response) {
console.log("metadata GET response:");
console.log(response);
}
});
// (2) POST requests do NOT work with my code.
// Originally based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
// Modified per API description at: http://fenixapps2.fao.org/api/v1.0/
$.ajax({
url: "http://fenixapps2.fao.org/api/v1.0/en/data/",
traditional: true,
data: {
"datasource": "production", //test
"output_type": "objects", //arrays
"api_key": "n.a.",
"client_key": "n.a.",
"lang": "en",
//"domain_code":"QC", //domain_code (from example page - http://faostat.github.io/faostat-api/) replaced by domain_codes?
"domain_codes": ["'QC'"],
//"thousand_separator": ",", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
//"decimal_separator": ".", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
"decimal_places": "2",
"List1Codes": ["'33'"],
"List2Codes": ["'2510'"],
"List3Codes": ["'15'"],
"List4Codes": ["'2007'","'2008'","'2009'","'2010'","'2011'","'2012'","'2013'","'2014'"],
"List5Codes": null,
"List6Codes": null,
"List7Codes": null,
"null_values": true,
//"group_by"
//"order_by"
//"operator"
"page_size":"100",
"limit": "10",
"page_number":1
//"show_codes"
//"show_flags"
//"show_unit"
},
type: 'POST',
success: function(response) {
console.log("data POST response:");
console.log(response);
}
});
}
</script>
</head>
<body onload='test();'>
<div id='out'></div>
</body>
---UPDATE---
I have tried changing the data section within $.ajax() so that the url created exactly matches the format of that of the cURL example from the FAO 'Example' page (http://faostat.github.io/faostat-api/). However, this has not altered the API's response. My updated code is included below -- the new console.log(urlPlusData); line I believe should reflect the full url that the code is generating for the POST.
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascript'>
function test() {
// (1) GET requests work fine.
// Based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
$.ajax({
type: 'GET',
url: 'http://fenixapps2.fao.org/api/v1.0/en/classifications/QC',
success: function(response) {
console.log("metadata GET response:");
console.log(response);
}
});
// (2) POST requests do NOT work with my code.
// Originally based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
// Modified per API description at: http://fenixapps2.fao.org/api/v1.0/
$.ajax({
url: "http://fenixapps2.fao.org/api/v1.0/en/data",
traditional: true,
data: {
"datasource": "production", //test
"output_type": "objects", //arrays
"api_key": "n.a.",
"client_key": "n.a.",
"lang": "en",
//"domain_code":"QC", //domain_code (from example page) replaced by domain_codes?
"domain_codes": ["QC"],
//"thousand_separator": ",", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
//"decimal_separator": ".", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
"decimal_places": "2",
"List1Codes": ["33"],
"List2Codes": ["2510"],
"List3Codes": ["15"],
"List4Codes": ["2007","2008","2009","2010","2011","2012"],
"List5Codes": ["null"],
"List6Codes": ["null"],
"List7Codes": ["null"],
"null_values": true,
//"group_by"
//"order_by"
//"operator"
"page_size":"100",
"limit": "10",
"page_number":"1"
//"show_codes"
//"show_flags"
//"show_unit"
},
beforeSend: function (jqXHR, settings) {
urlPlusData = settings.url + "?" + settings.data;
},
type: 'POST',
success: function(response) {
console.log("data POST response:");
console.log(urlPlusData);
console.log(response);
}
});
}
</script>
</head>
<body onload='test();'>
<div id='out'></div>
</body>

Project Oxford - HTTP 404 when calling Computer Vision API through Javascript

I am trying to get JSON data from Microoft Project Oxford through a API call. I followed the API reference but when I make a call I get a 404 error.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "All",
};
$.ajax({
url: "https://api.projectoxford.ai/vision/v1/analyses&" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","0000000000000000");
},
type: "POST",
// Request body
data: '{ "Url": "http://www.sweetheartmotors.ca/sites/default/files/audi_PNG1736.png" }',
})
.done(function(data) {
alert("success");
//display data
console(data);
})
.fail(function() {
alert("error");
});
});
</script>
What is stopping me from making the call?
You need to change the URL to end in a question mark, rather than an ampersand: https://api.projectoxford.ai/vision/v1/analyses?
Unfortunately most of the samples on the projectoxford.ai site contain this error.

ajax request to Microsoft Emotion API in javascript

I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.
The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"
Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>

Categories

Resources