Home > Enterprise >  fetch image from URL Javascript
fetch image from URL Javascript

Time:08-18

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

CodePudding user response:

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)

CodePudding user response:

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