Working with Computer Vision Thumbnails API repsonse data in JavaScript - javascript

I'm using the Microsoft Cognitive Computer Vision API (the thumbnails function).
I'm trying to use JavaScript and I cannot make sense of the response.
My entire HTML document with embedded JS code is as follows:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<button id="btn">Click here</button>
<p id="response">
<script type="text/javascript">
$('#btn').click(function () {
$.ajax({
url: "https://api.projectoxford.ai/vision/v1.0/generateThumbnail?width=100&height=100&smartCropping=true",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "382f5abd65f74494935027f65a41a4bc");
},
type: "POST",
data: '{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}'
})
.done(function (response) {
$("#response").text(response);
})
.fail(function (error) {
$("#response").text(error);
});
});
</script>
</body>
</html>
The response I'm getting does not appear to be JSON, it look like this:
How can I work with the response from this API such that I get the image as a base 64 string that I can set to be the src on an image element.
It will end up being something like this but I do not know how to get the <base64string> bit.
<img src="data:image/png;base64,<base64string>">
I've tried everything in the api test console at https://dev.projectoxford.ai/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fb/console and it seems to work fine.

I think the problem is that jQuery converts the argument passed to .done into a string – not sure how to stop it doing that. You could try converting that string back to a binary object but that doesn't feel right or you could work out how to get the raw response from jQuery.
I tried this using XMLHttpRequest (which works):
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.response, typeof this.response);
var response = document.querySelector('#response');
var img = new Image();
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
response.appendChild(img);
}
}
xhr.open('POST', 'https://api.projectoxford.ai/vision/v1.0/generateThumbnail?width=5&height=5&smartCropping=true');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Ocp-Apim-Subscription-Key", "382f5abd65f74494935027f65a41a4bc");
xhr.responseType = 'blob';
xhr.send('{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}');

The response from the service is a binary JPEG image, indicated by the response header "Content-Type: image/jpeg".
For advice on how to encode this as base64, and display it, you could look to these related answers:
Base64 encoding
Displaying an image from a web-service

Related

Data not displaying in JavaScript API

I am making a Pokedex API as a side project and I can not display the data needed to display in the different text boxes. I am using a GET request to request the height, weight, type, and ability.
<script>
$("button").click( function(){
var pokemonName = $('pokemon').val(pokemon);
event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName){
var request = new XMLHttpRequest()
//GET request with link
request.open('GET','https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload =function(){
var data = JSON.parse(this.response)
if(request.status >= 200 && request.status <= 400)
{
// outputs data
$(pokemonheight).val(response.height)
$(pokemonweight).val(response.weight)
$(pokemonAblity).val(response.ability)
$(pokemonType).val(response.type)
}
else
{
alert ("Error");
}
request.send();
}
}
</script>
</html>
I have tried setting a variable that would be equal to the response JSON element and then input that into the value of the textbox.
I do not have anything returned as expected or input displayed in the console if declared.
Issue(s)
There were a few issues with your code:
var pokemonName = $('pokemon').val(pokemon); you are setting the value of some element named pokemon (not valid) here
var data = JSON.parse(this.response); where is this.response being set? Shouldn't we be receiving response in the callback?
request.send(); is inside of the onload event, so the request never gets sent
Critiques
My main critique here is that you included a fairly large library (jQuery), and didn't utilize it to make the request. $.ajax is well documented and cleans up a lot of the intricacies of XMLHttpRequest.
The solution
$("button").click(function() {
var pokemonName = $('#pokemon').val();
//event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName) {
var request = new XMLHttpRequest()
//GET request with link
request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload = function(response) {
var data = JSON.parse(response.currentTarget.response)
if (request.status >= 200 && request.status <= 400) {
// outputs data
console.log(data)
} else {
alert("Error");
}
}
request.send();
}
<input id="pokemon" value="12" />
<button>search</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Taking all the above issues into account, I was able to get a working example of what it should ultimately look like.
Hope this helps!

multipart HTTP request with microsoft graph javascript sdk

I'm trying to use the Microsoft Graph JavaScript SDK to create a page in OneNote with images, which OneNote requires a multipart request for. I've created a FormData object with all the data I'm trying to send.
The request goes through when I send it up myself as follows:
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Authorization", "Bearer" + token);
xhr.onreadystatechange = function() {
//Call a function when the state changes
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
} else {
// handle case
}
};
// dataToSend = FormData object containing data
// (as Blobs), including the page HTML in a
// "Presentation" part as specified
xhr.send(dataToSend);
However, since I'm using the Graph SDK to make all my other requests, I'm wondering if there's a way to do the multipart request with the SDK as well. So far, this is what I've tried:
this.client
.api(pagesURL)
.version("beta")
.header("Content-Type", "text/html")
.post(dataToSend);
Investigating the request in Fiddler shows that the request body contains [object, Object], not the data formatted as a multipart request. Any help on how to get the FormData object into the request properly using the SDK/ guidance on whether this is possible would be greatly appreciated!
I believe this is what you're looking for:
this.client
.api("https://graph.microsoft.com/beta/me/notes/sections/{Section ID}/pages")
.header("Content-Type", "application/xhtml+xml")
.header("boundary", "MyPartBoundary")
.post(dataToSend);
This snippet was adapted from the multi-part unit test used by the SDK itself. You can find that test at https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/spec/types/OneNote.ts
Update the microsoft-graph-client to latest version and try something like this.
const HTMLPageContent =
`<!DOCTYPE html>
<html>
<head>
<title>A page with rendered images</title>
</head>
<body>
<p>Here is an image uploaded as <b>binary data</b>:</p>
<img src="name:imageBlock1" alt="an image on the page" />
</body>
</html>`;
let sectionId = "<Your_OneNote_Page_Section_Id>";
let formData = new FormData();
let htmlBlob = new Blob([HTMLPageContent], {
type: "text/html"
});
formData.append("Presentation", htmlBlob);
formData.append("imageBlock1", file);
client
.api(`/me/onenote/sections/${sectionId}/pages`)
.post(formData)
.then((json) => {
console.log(json);
return Promise.resolve();
});

Getting a file type from URL

I need To find out the file type from a url image located on my server without checking the extension, but I'm not sure how to do that without putting the image into an "input" like this:
<input type="file" id="upload_file" accept="image/*|audio/*|video/*"/>
<input type="submit" onclick="sumbit()"/>
<script type="text/javascript">
function sumbit(){
var file_Element = document.getElementById("upload_file")
alert(file_Element.files[0].type);
//alert: image/png
}
<script>
I understand that ".type" only work with a file object, so how do I turn the url image into an object like this image of google's logo: https://www.google.ca/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png.
Do I need to use a ajax/flilereader? if so, how?
Assuming your Content-Type HTTP headers are accurate, you can avoid downloading the whole file just to check the type by creating a HEAD request. Assuming you don't also need the whole file for something else, this could be a much-quicker operation, especially for large files.
Working Example:
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onload = function() {
var contentType = xhr.getResponseHeader('Content-Type');
console.log(contentType);
};
xhr.send();
Alternately, you can achieve a similar result with a regular GET request by calling abort on the AJAX request object before it loads the whole body (in any remotely recent browser anyway).
Alternate Working Example:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onreadystatechange = function() {
// Wait for header to become available.
var contentType = xhr.getResponseHeader('Content-Type');
if (contentType) {
// Stop downloading, the headers are all we need.
xhr.abort();
console.log(contentType);
}
};
xhr.send();
The accept attribute value is not valid. There should be comma , instead of pipe | character separating MIME types.
You can use change event to check File object .type
<input type="file" id="upload_file" accept="image/*,audio/*,video/*"/>
<input type="submit" onclick="submit()"/>
<script type="text/javascript">
var elem = document.getElementById("upload_file");
elem.onchange = function(e) {
console.log(e.target.files[0].type)
}
function submit() {
if (elem.files.length) {
console.log(elem.files[0].type)
} else {
alert("no files selected")
}
}
</script>
Use XHR to download the file, and then use the Blob api to determine the mime type:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
//Here's the type
console.log(xhr.response.type);
};
xhr.send();

How to preview text excerpt from large file in Javascript

I'm fairly new to JS (& SO), but I have a webpage where I upload a file sometimes as big as 500mb. The user takes a file from their OS and I want to preview the file in a <pre> </pre> box before sending off to a http endpoint, but for performance reasons I'd rather not read the entire file and then slice out the first few lines.
If possible, I'd like to just read the first few lines instead. This could be the first few bytes too if that's easier, there's no strict cut off point.
Currently I do this to read the file:
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
document.getElementById("mailingFileText").innerHTML = evt.target.result;
};
}
...and I set it inside this:
<pre class="pre-scrollable" style="white-space: pre-wrap;">
<p id="mailingFileText"></p>
</pre>
But this isn't overly feasible for really large files. Can anyone help?
Make sure to test your site
Code a Example:
jQuery
$(window).ready(function() {
$.ajax({
url: './wiki-stevenjobs.txt',
type: 'GET',
contentType: 'text/txt; charset=UTF-8',
success: function(data) {
$('p#mailingFileText').html(data);
},
error: function(err){
$('p#mailingFileText').html(err);
}
});
});
OR
Javascript Pure:
var xhr = new XMLHttpRequest();
xhr.open("GET", "./wiki-stevenjobs.txt", true);
xhr.setRequestHeader("Content-Type", "text/txt; charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("mailingFileText").innerHTML = xhr.response;
}
};
xhr.send();
500mb too much more 10minutes is depend a server, is best 10mb minimum.

How to call a REST web service API from JavaScript?

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch() method. It takes two arguments:
A URL or an object representing the request.
Optional init object containing the method, headers, body etc.
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Your Javascript:
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Your Button action::
<button type="submit" onclick="UserAction()">Search</button>
For more info go through the following link (Updated 2017/01/11)
Here is another Javascript REST API Call with authentication using json:
<script type="text/javascript" language="javascript">
function send()
{
var urlvariable;
urlvariable = "text";
var ItemJSON;
ItemJSON = '[ { "Id": 1, "ProductID": "1", "Quantity": 1, }, { "Id": 1, "ProductID": "2", "Quantity": 2, }]';
URL = "https://testrestapi.com/additems?var=" + urlvariable; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
I think add if (this.readyState == 4 && this.status == 200) to wait is better:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("GET", "your url", true);
xhttp.send();
If that helps anyone, if you are ok with an external library then I can vouch for Axios, which has a pretty clean API and rich documentation to deal with REST calls, here's an example below:-
const axios = require('axios');
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
});
Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.
We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
// Begin accessing JSON data here
}
}
// Send request
request.send()
By far, the easiest for me is Axios. You can download the node module or use the CDN for your simpler projects.
CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Code example for GET/POST:
let postData ={key: "some value"}
axios.get(url).then(response =>{
//Do stuff with the response.
})
axios.post(url, postData).then(response=>{
//Do stuff with the response.
});
Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method. Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript. Here is an example that assumes the REST API is in file REST.php:
<body>
<h2>REST-test</h2>
<input type=button onclick="document.getElementById('a').submit();"
value="Do It">
<form id=a action="REST.php" method=post>
<input type=hidden name="arg" value="val">
</form>
</body>
Note that this example will replace the page with the output from page REST.php.
I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page. But it's certainly simple.
Usual way is to go with PHP and ajax. But for your requirement, below will work fine.
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>

Categories