How I can make this
var imageurl = 'https://tr.wikipedia.org/wiki/'
let queryimage = `${imageurl}Dosya:${cityName}.jpg`
console.log(queryimage)
When ı look console ı see this ;
https://tr.wikipedia.org/wiki/Dosya:england.jpg
thats ok but now
How ı can download image on this page https://tr.wikipedia.org/wiki/Dosya:england.jpg
This is your way :
// Your url must be like this : 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/England.jpg/800px-England.jpg'
let cityName = 'England';
let imageurl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/'
let queryimage = `${imageurl}${cityName}.jpg/800px-${cityName}.jpg`
let img = document.getElementById('image');
img.setAttribute('src',queryimage)
You can use MediaWiki's Action API to retrieve information about the images in these pages and grab the source of this image.
async function grabImageInfo(pageTitle) {
const resp = await fetch(`https://tr.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=${pageTitle}&piprop=original&format=json&origin=*`);
if (!resp.ok) {
throw new Error("Network Error");
}
return resp.json();
}
async function grabImageSource(pageTitle) {
const imageInfo = await grabImageInfo(pageTitle);
return Object.values(imageInfo.query.pages)[0].original.source;
}
const select = document.querySelector("select");
const img = document.querySelector("img");
const a = document.querySelector("a");
async function handleChange() {
try {
const pageTitle = `Dosya:${select.value}.jpg`;
const imgUrl = await grabImageSource(pageTitle);
img.src = imgUrl;
a.href = `https://tr.wikipedia.org/wiki/${pageTitle}`
}
catch(err) {
console.error(err);
}
}
select.onchange = handleChange;
handleChange();
<select>
<option>England</option>
<option>Italy</option>
<option>Germany</option>
<option>Flower</option>
<option>Cat</option>
</select><br>
<a>Go to Wikipedia's page</a><br>
<img>
Related
I'm new to async and await. I'm working on a recipe website using an api and fetch. need help to add async await to the fetch. I'm using spoonacular api.
there are no errors just want to add async await.
function retrieve(e) {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
data.results.forEach((results) => {
let li = document.createElement("li");
let a = document.createElement("a");
let div = document.createElement("div");
let img = document.createElement("img");
let btn = document.createElement("button");
// styling
div.className = "newsdiv";
img.className = "newsimg";
btn.className = "btns";
li.style.width = "300px";
a.setAttribute("href", results.sourceUrl);
a.setAttribute("target", "_blank");
img.setAttribute("src", results.image);
div.textContent = results.title;
// btn.prepend(br);
div.appendChild(a);
div.prepend(img);
li.prepend(div);
btn.textContent = "Get Recipe";
div.appendChild(btn);
a.appendChild(btn);
newsList.appendChild(li);
});
})
.catch((error) => {
console.log(error);
});
}
Look at below snippet. This will be useful to your solution. In the function you may do whatever operations you want.
const retrieve = async (e) => {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
const response = await fetch(url);
const myJson = await response.json(); //extract JSON from the http response
console.log(myjson);
}
retrieve(null);
I am trying to add the link on the image or title. when I click on the image/text it should take me to another page index.html.
How can I do that?
const apiUrl = 'https://api.themoviedb.org/3/discover/movie
sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1;
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?
&api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url){
fetch(url).then(res => res.json())
.then(function(data){
console.log(data.results);
data.results.forEach(element => {
const el = document.createElement('div');
const image = document.createElement('img');
const text = document.createElement('h2');
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = '';
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
Fixed your code, the tick was to add a element instead of with the desired href
const apiUrl =
"https://api.themoviedb.org/3/discover/moviesort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1";
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
"https://api.themoviedb.org/3/search/movie? &api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url) {
fetch(url)
.then((res) => res.json())
.then(function (data) {
console.log(data.results);
data.results.forEach((element) => {
el = document.createElement("a");
el.href = "https://example.com"
const image = document.createElement("img");
const text = document.createElement("h2");
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = "";
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
I have the src (data) of an image, that is not saved yet and doesn't have a path yet.
I would like to know the future ipfs hash that will result from it once it is saved and sent to ipfs.
So far I have done this, but the hashes don't match.
import { saveAs } from 'file-saver';
const dagPB = require('ipld-dag-pb')
const UnixFS = require('ipfs-unixfs')
func = async () => {
let bgImage = await import(`./images/bg.png`);
let bodyImage = await import(`./images/body.png`);
let headImage = await import(`./images/head.png`);
let eyesImage = await import(`./images/eye.png`);
let mouthImage = await import(`./images/mouth.png`);
let levelImage = await import(`./images/level.png`);
src = await mergeImages([
bgImage.default,
bodyImage.default,
headImage.default,
eyesImage.default,
mouthImage.default,
levelImage.default,
]);
image.src = src;
saveAs(image.src, `photo.png`);
const fileBuffer = Buffer.from(image.src)
const file = new UnixFS('file', fileBuffer)
dagPB.DAGNode.create(file.marshal(), (err, node) => {
if(err) return console.error(err)
console.log(node._cid.toBaseEncodedString())
})
}
What is missing or wrong ?
And here is what I did.
const Hash = require('ipfs-only-hash')
func = async () => {
let bgImage = await import(`./images/bg${ex}.png`);
let bodyImage = await import(`./images/body${ex}.png`);
let headImage = await import(`./images/head${ex}.png`);
let eyesImage = await import(`./images/eye${ex}.png`);
let mouthImage = await import(`./images/mouth${ex}.png`);
let levelImage = await import(`./images/level${ex}.png`);
src = await mergeImages([
bgImage.default,
bodyImage.default,
headImage.default,
eyesImage.default,
mouthImage.default,
levelImage.default,
]);
const endOfPrefix = src.indexOf(",");
const cleanStrData = src.slice(endOfPrefix+1);
const imageData = Buffer.from(cleanStrData, "base64");
const imageHash = await Hash.of(imageData);
console.log("fetch data CID: " + imageHash)
}
Remove the header of the data, to keep only the data and then hash it it with ipfs-hash-only.
The image hash is then written in the .json and the same process is used to hash the .json and know before hand the metadata's ipfs address.
I have put the code below my for a simple weather app using Open Weather
The code to get the icon code from the JSON works in the first block but not in the second?
i can console log the variable no problem but when i am trying to display the icon it isnt loading the png file?
The line in question is
let icon1 = jsonResponse.list[8].weather[0].icon
nextDayWeather.src = `/resources/icons/${icon1}.png`
full code for reference including same code working in an earlier function
async function getWeather(input) {
const city = input
try {
const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=`)
if (response.ok) {
const jsonResponse = await response.json()
const {icon} = jsonResponse.weather[0]
currTemp.innerText = Math.floor(jsonResponse.main.temp - 273)
currWind.innerText = jsonResponse.wind.speed
currWeather.src = `/resources/icons/${icon}.png`
return
}
throw new Error('Request Failed')
} catch(error) {
window.location = '/'
}
}
async function extraWeather(input) {
const city = input
try {
const response = await fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=`)
if (response.ok){
const jsonResponse = await response.json()
let icon1 = jsonResponse.list[8].weather[0].icon
let icon2 = jsonResponse.list[16].weather[0].icon
let icon3 = jsonResponse.list[24].weather[0].icon
nextDayWeather.src = `/resources/icons/${icon1}.png` //needs fixing??
nextDayWind.innerText = jsonResponse.list[8].wind.speed
nextDayTemp.innerText = Math.floor(jsonResponse.list[8].main.temp - 273)
nextDayWeather2.src = `/resources/icons/${icon2}.png`
nextDayWind2.innerText = jsonResponse.list[16].wind.speed
nextDayTemp2.innerText = Math.floor(jsonResponse.list[16].main.temp - 273)
nextDayWeather3.src = `/resources/icons/${icon3}.png`
nextDayWind3.innerText = jsonResponse.list[24].wind.speed
nextDayTemp3.innerText = Math.floor(jsonResponse.list[24].main.temp - 273)
console.log(jsonResponse.list[16].weather[0].icon)
return
}
throw new Error ('error') }
catch(error){
console.log(error)
}
}
I tried to convert a base64 string generated from pdf file using FileReader.readAsDataURL() to its original format.In NodeJS I did it like this and it was able generated the pdf to its initial state.
filebuffer = "data:application/pdf;base64,JVBERi0xLjQKJSDi48/..........."
let base64file = fileBuffer.split(';base64,').pop();
fs.writeFileSync('download.pdf',base64file,{encoding:'base64'},function(err){
if(err === null){
console.log("file created");
return;
}
else{
console.log(err);
return;
}
})
But i tried to do it in HTML + Javascript in this way.But in this way , pdf was empty/no letter wasn't in it
let stringval = "data:application/pdf;base64,JVBERi0xLjQKJSDi48/..........."
let encodedString = stringval.split(';base64,').pop();
let data = atob(encodedString);
let blob = new Blob([data]);
// //if you need a literal File object
let file = new File([blob], "filename");
link.href = URL.createObjectURL(file);
link.download = 'filename';
I was Capturing file and converting to base64 string in this way:
captureFile: function () {
event.preventDefault();
const file = event.target.files[0];
$("#labelinput1").html(file.name);
const reader = new window.FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
var x = reader.result.toString();
App.buffer2 = x;
console.log("buffer", App.buffer);
};}
Then after clicking a button , I added the buffer to IPFS node
addfile: async function () {
if (App.buffer2 === null) return;
App.node = await window.Ipfs.create()
App.node.add(App.buffer2, function (errx, resipfs) {
if (errx === null) {
console.log(resipfs[0].hash);
App.buffer2 = null;
return App.showInfo(resipfs[0].hash);
}
else {
return App.showError(errx.message.toString() + errx.stack.toString());
}
});
}
using the IPFS HASH i can get back the base64 encoded string , I retrieved this string in this way:
ipfsfiledownload: async function () {
var filebuffer = await App.node.cat(hashtext);
var stringval = filebuffer.toString();
//convert this string to main file
}
I used Truffle Petshop and write those functions in top of it. Here is a IPFS hash QmfSefUiwjV44hpfnHyUngGATyHm9M4vN3PzF1mpe59Nn1. you can try out this Hash value in nodejs with this code
const IPFS = require('ipfs');
const fs = require('fs');
const main = async() => {
const node = await IPFS.create()
var fileBuffer = await
node.cat('QmfSefUiwjV44hpfnHyUngGATyHm9M4vN3PzF1mpe59Nn1')
fileBuffer = fileBuffer.toString()
let base64file = fileBuffer.split(';base64,').pop();
fs.writeFileSync('download.pdf',base64file, {encoding:'base64'},function(err){
if(err === null){
console.log("file created");
return;
}
else{
console.log(err);
return;
}
})
}
main()
You can find the full code here.
What I am doing wrong and how to solve it?
After converting the base64 string using atob() , I converted it to Uint8Array Then created the blob and file . It seems to work now ..
Here is the full code :
ipfsfiledownload: async function () {
var hashtext = document.getElementById("id_ipfshash").value //getting the IPFS HASH
var link = document.getElementById("downloadLink");
if (hashtext === null) return
var filebuffer = await App.node.cat(hashtext); //getting the base64 string from IPFS
var stringval = filebuffer.toString();
console.log(stringval);
let encodedString = stringval.split(',')[1]; //getting the base64 hash
let mimetype = stringval.split(',')[0].split(':')[1].split(';')[0]; //getting the mime type
let data = atob(encodedString); //ascii to binary
var ab = new ArrayBuffer(data.length);
var ia = new Uint8Array(ab);
//converting to Uint8Array
for(var i = 0;i<data.length;i++){
ia[i] = data.charCodeAt(i);
}
let blob = new Blob([ia],{ "type": mimetype});
let filename = 'filename.' + App.getExtension(mimetype);
let file = new File([blob], filename);
link.href = window.URL.createObjectURL(file);
link.download = filename;
link.click();
}