Getting the output from an API request (client-side) - javascript

Note: I am inexperienced with APIs, JSON, REST, etc.
I am trying to implement FilePreviews into my site. Its purpose is to take the url for any file type and convert it into a JPG or PNG.
JavaScript
var previews = new FilePreviews({
debug: true,
apiKey: 'MY_API_KEY'
});
var url = 'http://i.imgur.com/HQB8wtI.jpg';
var options = {
size: {
width: 100,
height: 999
},
metadata: ['exif', 'ocr', 'psd'],
format: 'jpg'
};
previews.generate(url, options);
The request is received by the developer's app. The following results are shown in the site dashboard of the developer's app:
{
"preview": {
"resized": true,
"size": {
"height": "178",
"width": "100"
},
"page": 1,
"url": "https://s3-us-west-2.amazonaws.com/[removed for privacy]/ec210ecf45d9d190539a241462c621f75adf2d4f835fb394a8d738d09fd412d6/HQB8wtI_100x999_1.jpg",
"requested_size": "100x999",
"original_size": {
"height": "1024",
"width": "576"
}
},
"id": "25841aca-e176-4cf7-ac1d-b01ce604a765",
"user_data": null,
"status": "success",
"url": "https://api.filepreviews.io/v2/previews/25841aca-e176-4cf7-ac1d-b01ce604a765/",
"thumbnails": [
{
"resized": true,
"size": {
"height": "178",
"width": "100"
},
"page": 1,
"url": "https://s3-us-west-2.amazonaws.com/[removed for privacy]/ec210ecf45d9d190539a241462c621f75adf2d4f835fb394a8d738d09fd412d6/HQB8wtI_100x999_1.jpg",
"requested_size": "100x999",
"original_size": {
"height": "1024",
"width": "576"
}
}
],
"original_file": {
"metadata": {
"ocr": null,
"psd": null,
"exif": null
},
"size": 82022,
"extension": "jpg",
"total_pages": 1,
"encoding": "binary",
"name": "HQB8wtI",
"mimetype": "image/jpeg",
"type": "image"
}
}
My question is: How do I get the url for the file preview into my site? Each file is referenced dynamically and there will be many on a page for most areas of my site. There seems to be no consistency in how FilePreviews is generating the folder on AWS S3, so I can't even use a clever PHP fix to solve it.
Anyone care to assist and show me the ways of this programming world?

I don't have experience with FilePreviews, but this is how I expect it should work.
First, you add an image tag in your HTML, at the spot where you want the thumbnail to appear. Give it an id, for example "thumb":
<img id="thumb"/>
Then, modify the last line of your script as follows:
previews.generate(url, options, onPreviewReceived);
The third parameter is a callback function we must define elsewhere in the script. I have called it onPreviewReceived, but you can choose your own name. It is called when the result is received. You can define the callback function as follows:
function onPreviewReceived(err, result) {
if (!err) {
var thumbnailUrl = result.thumbnails[0].url; // but see assumption
document.getElementById("thumb").setAttribute("src", thumbnailUrl);
}
}
This function assigns the url, obtained from the result, to the src attribute of the img tag.
Assumption: I expect the 'result' to be as described in your question. However, the client library documentation indicates that you will get a different result and that you should have a thumbnailUrl assignment like this:
var thumbnailUrl = result.previewUrl;
So please try that as well.

Related

Where is image data in React?

Im using the following function to upload an image to our application:
const result = await ImagePicker.launchCameraAsync({
allowsEditing:true,
});
This returns the following object:
Object {
"cancelled": false,
"height": 3200,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sepbaa%252Frepoflex/ImagePicker/ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"width": 2400,
}
Afterwards we need to upload the image to our backend, but we don't know where the image data is. If we do a fetch to the uri from the previous object, it returns the following:
Object {
"_bodyBlob": Object {
"_data": Object {
"collector": Object {},
"blobId": "c0e241fa-9b39-4aed-9860-793a393408dd",
"lastModified": 0,
"name": "ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"offset": 0,
"size": 4864483,
"type": "image/jpeg",
},
},
"_bodyInit": Object {
"_data": Object {
"collector": Object {},
"blobId": "c0e241fa-9b39-4aed-9860-793a393408dd",
"lastModified": 0,
"name": "ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"offset": 0,
"size": 4864483,
"type": "image/jpeg",
},
},
"bodyUsed": true,
"headers": Object {
"map": Object {
"content-type": "image/jpeg",
},
},
"ok": false,
"status": 0,
"type": "default",
"url": "",
}
We need to send to our backend the raw image bytes. Where is that data stored? How can we retrieve it?
For uploading it to backend you need to do like this
const form = new FormData();
form.append({
name: "SampleImage.jpg", // Name of file
uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sepbaa%252Frepoflex/ImagePicker/ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg", // URI of the file
type: "image/jpg", // MIME type of the file
})
Now you just simply have to perform a POST request with this form as body
Also in the backend you can access it like this
req.file // Depends on the backend you are using ...

Loading a set of images onto an html page from a json file but switch to a different set of images from the same json

I use a local html page as a way to keep track of how many and what shinies i've found. before i made a seperate page with new pokemon's in it if the previous page was full.
What i'm trying to accomplish
Recently i've been changing this system so only one page is used and it loads the image data from a json file.
every pokemon inside the json has its own id(eg: id 1, all the way till id 30):
{
"images": {
"P1": [
{
"id": "1", "name": "snubbull", "size": "small",
"type": "fairy", "gender": "male_gender",
"gen": "xy", "huntType": "Soft Resets",
"lv": "5", "nickname": "none",
"prevEvo": "none"
},
{
"id": " 2", "name": "granbull", "size": "small",
"type": "fairy", "gender": "male_gender",
"gen": "xy", "huntType": "Soft Resets",
"lv": "5", "nickname": "none",
"prevEvo": "none"
}
],
"P2": [
{
"id": "1", "name": "zubat", "size": "small",
"type": "poison_flying", "gender": "female_gender",
"gen": "xy", "huntType": "Soft Resets",
"lv": "5", "nickname": "none",
"prevEvo": "none"
},
{
"id": "2", "name": "golbat", "size": "small",
"type": "poison_flying", "gender": "female_gender",
"gen": "xy", "huntType": "Soft Resets",
"lv": "5", "nickname": "none",
"prevEvo": "none"
}
]
}
}
in the above example i made the json a little shorter to prevent this page from becoming super long.
"P1" stands for for Page 1 and "P2" for Page 2(you get the idea).
my problem here is that the page should load "P1" as default, but when i
click the previous or next page buttons it needs to unload all of the currently loaded images and load in the next 30 images (in this case from "P2").
<script src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var basePath = "sprites/"
var baseExt = ".gif"
function load(){
$(document).ready(function () {
var jsonURL = "db.json";
$.getJSON(jsonURL, function (json){
var imgList= "";
$.each(json.images.P1, function () {
imgList += '<img src= "' + basePath + this.gen + "ani/" + this.size + "/" + this.name + baseExt + '" class="RESIZER ' + this.gender + ' ' + this.type + '">';
});
$('.pkm_tile').append(imgList);
});
});
}
load()
var requestedPage = 1;
function switchPage(inp){
if(inp==1){
requestedPage++;
}else if(inp==0){
requestedPage--;
}
if(requestedPage >= 1){
load();
}else{
alert("couldn't load page " + requestedPage);
requestedPage = 1;
load();
}
}
</script>
so the plan was to put the code that executes the image loading inside a function that is executed at the start, but also re-executed when pressing the Previous/Next Page buttons.
here's the code for the buttons:
<button class="backbutton" onclick="switchPage(0);"><p> ← Previous Page </p></button>
<button class="nextbutton" onclick="switchPage(1);"><p> Next Page→ </p></button>
none of this has actually worked for me, apart from displaying an alert when trying to go lower than page 1.
if anyone knows how to this please let me know, if anyone suggests using something besides jquery to load the data from the json file, i'd be willing to try it out as long as i can still use a json file.
this is my first post on stackoverflow(i dont post many questions on other forums either) so sorry if it's a bit long.
One last note:
I noticed that the page that does load only loads in firefox. When I load it in Google Chrome it doesn't even display page 1.
I'm also pretty new to jquery, json files, and JavaScript(on html pages),
so you'll probably see a few "nooby" mistakes :P

Why are some JSON attributes omitted?

I have a JSON object that I'm working with. It's the result of an HTTP GET request.
The expected results are the following:
{
"name": {
"type": "string"
},
"authors": {
"collection": "users",
"via": "IDPid"
},
"id": {
"type": "integer",
"autoIncrement": true,
"primaryKey": true,
"unique": true
}
}
The actual results are the following (The authors attribute is omitted):
{
"name": {
"type": "string"
},
"id": {
"type": "integer",
"autoIncrement": true,
"primaryKey": true,
"unique": true
}
}
Why did it take out the authors attribute?
However, when I debug this in Chrome, though the authors attributes is still omitted, I am able to execute console.log(response.authors) and it reads it fine.
Also, when I go to the Network tab on Chrome dev tools to see the response of the HTTP request, it shows the missing attribute in the response body just fine.
I found out the problem. It was because console.log doesn't run right away. It runs after some time. I had other code that modified the object, but console.log ran after that code for some reason, even though I wrote it before.

Using tumblr API (JSON) and $.getJSON to grab the most recent posts from my tumblr blog

I'm having trouble pulling in the content from my tumblr formatted as JSON. I registered an API key from tumblr, and have the right API link, but am missing something in the $.getJSON. Below I'll show what my JSON and my jQuery both look like.
Here's what my JSON looks like:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "BLOG TITLE",
"name": "BLOG NAME",
"posts": 96,
"url": "http://BLOGTITLE.tumblr.com/",
"updated": 1370605005,
"description": "BLOG DESCRIPTION",
"ask": false,
"ask_anon": false,
"is_nsfw": false,
"share_likes": true,
"likes": 0
},
"posts": [
{
"blog_name": "BLOG NAME",
"id": 52373434879,
"post_url": "POST URL",
"slug": "POST SLUG",
"type": "photo",
"date": "2013-03-07 11:36:44 GMT",
"timestamp": 1370605004,
"state": "published",
"format": "html",
"reblog_key": "T0m0e51u",
"tags": [],
"short_url": "SHORT URL",
"highlighted": [],
"note_count": 1,
"caption": "PHOTO CAPTION TEXT DESCRIPTION",
"image_permalink": "http://BLOGTITLE.tumblr.com/image/52373434879",
"photos": [
{
"caption": "",
"alt_sizes": [
{
"width": 640,
"height": 960,
"url": "http://31.media.tumblr.com/.../...jpg"
},
{
"width": 500,
"height": 750,
"url": "http://31.media.tumblr.com/.../..._500.jpg"
},
{
"width": 400,
"height": 600,
"url": "http://24.media.tumblr.com/.../..._400.jpg"
},
{
"width": 250,
"height": 375,
"url": "http://31.media.tumblr.com/.../..._250.jpg"
},
{
"width": 100,
"height": 150,
"url": "http://24.media.tumblr.com/.../..._100.jpg"
},
{
"width": 75,
"height": 75,
"url": "http://24.media.tumblr.com/.../..._75sq.jpg"
}
],
"original_size": {
"width": 640,
"height": 960,
"url": "http://31.media.tumblr.com/.../..._1280.jpg"
}
}
]
},
Here's what my jQuery looks like:
jQuery(document).ready(function(){
var url = "http://api.tumblr.com/v2/blog/BLOGNAME.tumblr.com/posts?api_key=APIKEY&limit=5";
var src;
var caption;
$.getJSON(url, function(results){
$.each(results.response, function(i,item){
src = "posts.photos.alt_sizes.url";
caption = posts.caption;
$("<img/>").attr("src", src).appendTo("#submissions").wrap('<div class="postImage"></div>').after('<span class="postCaption">' + caption + '</div>');
});
HTML:
<div id="submissions"></div>
I am pretty sure that the problem is in the $.getJSON or $.each, but I can't figure out exactly what. Any help?
Thanks.
You are probably getting an error because you are trying to access the variable post which is not defined. And you are iterating over results.response, but it looks like you want to iterate over results.response.posts, which is an array of blog posts.
Furthermore, each post seems to have an photos array from which you have to choose the element with photo size you want to have.
Example:
$.each(results.response.posts, function(i, item){
var src = item.photos[0].alt_sizes[0].url; // first picture, first size
var caption = item.caption;
$("<img/>").attr("src", src).appendTo("#submissions").wrap('<div class="postImage"></div>').after('<span class="postCaption">' + caption + '</div>');
});
Of course if a post doesn't have a photo and the array is empty, you will get a runtime error, but I assume you will account for these cases.
The other problem is that you cannot make an Ajax request to the tumblr API since it is an external domain. However, the tumblr API supports JSONP, so if you add &callback=? to the URL, you tell jQuery to use JSONP instead:
var url = "[...]/posts?api_key=APIKEY&limit=5&callback=?";
I recommend to read some basic JavaScript tutorials to learn how to work with arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Predefined Core Objects: Array object

How to read JSON in order to get the last video from YouTube

I'd like to extract the last video (only video), with title, description, etc.
I am using JSON Data API from YouTube Data API and using the Video Upload By User Feed in order to get the data.
I got from youtube a JSON (object?) about my Youtube's space and tried to read the JSON text, but its a suicide.
My code is :
<div id="ytContent"></div>
<script type="text/javascript">
function showMyVideos(data) {
var feed = data.feed;
var entries = feed.entry || [];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t;
$('#ytContent').append(title + "<br />");
}
}
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&format=5&callback=showMyVideos"></script>
but if I try to do :
var p = eval("(" + data + ")");
alert(p);
I can't get a right parser. Why? How can I parse my JSON? I just need to understand which field I can use in order for me to get the last video from the feed. Also, hints/tips on getting the last video will also be helpful.
Thanks
You don't need to parse the data, it is already parsed.
The url inside your script tags gets rendered into a function call, passing the data object as a parameter: showMyVideos({ /* data object */ });.
Your problem is that you are trying to access the entry field in the data you are receiving (var entries = feed.entry || []), but there is no such field in data.feed:
var data = {
"version": "1.0",
"encoding": "UTF-8",
"feed": {
"xmlns": "http://www.w3.org/2005/Atom",
"xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
"id": {
"$t": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads"
},
"updated": {
"$t": "2011-09-06T08:05:27.303Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://gdata.youtube.com/schemas/2007#video"
}
],
"title": {
"$t": "Uploads by MYUSERNAME",
"type": "text"
},
"logo": {
"$t": "http://www.youtube.com/img/pic_youtubelogo_123x63.gif"
},
"link": [
{
"rel": "related",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/myusername"
},
{
"rel": "alternate",
"type": "text/html",
"href": "http://www.youtube.com/profile_videos?user=MYUSERNAME"
},
{
"rel": "http://schemas.google.com/g/2005#feed",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads"
},
{
"rel": "http://schemas.google.com/g/2005#batch",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads/batch"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&start-index=1&max-results=25&format=5"
}
],
"author": [
{
"name": {
"$t": "MYUSERNAME"
},
"uri": {
"$t": "http://gdata.youtube.com/feeds/users/myusername"
}
}
],
"generator": {
"$t": "YouTube data API",
"version": "2.1",
"uri": "http://gdata.youtube.com/"
},
"openSearch$totalResults": {
"$t": 0
},
"openSearch$startIndex": {
"$t": 1
},
"openSearch$itemsPerPage": {
"$t": 25
}
}
}
When showMyVideos is called, data is already parsed. You don't need to parse it.
You don't get JSON! You get JavaScript!
If you execute it using eval(),the data is automatically passed to your showMyVideos function. You don't have to parse anything ;) The data is already parsed, its an object, not a string.
Based on the question, I am assuming you want to get the last video and show it as video player.
In order to show the last video, the possible steps are:
Include the script for the player itself
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script>
Create your callback function. Basically what Google does is getting the JSON, parse it and call your callback function that you specified in callback parameter in your http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&format=5&callback=showMyVideos. In your callback you would want to show the video player for the last video. Something like:
// function to load your video
function loadVideo(playerUrl, autoplay) {
swfobject.embedSWF(
playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
(autoplay?1:0), 'player', '290', '250', '9.0.0', false,
false, {allowfullscreen: 'true'});
}
// this is your callback function, Google call this function after parsing the JSON
// and passing it as data
function showMyVideos(data) {
var feed = data.feed;
var entries = feed.entry || [];
if (entries.length > 0) {
// show the video for the last entry
loadVideo(entries[entries.length-1].media$group.media$content[0].url, false);
}
}
Next you define somewhere where you want to put your video
<div id="playerContainer" style="width: 20em; height: 180px; float: left;">
<object id="player"></object>
</div>
Finally call the script that will invoke your callback. This should be the same as your code in the question
<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&format=5&callback=showMyVideos"></script>

Categories