简体   繁体   中英

Fetch image from API

Q1) In my reactjs application, I am trying to fetch an API from my backend Nodejs server. The API responds with an image file on request.

I can access and see image file on http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg

But in my reactjs client side I get this error on console log.

Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0

Reactjs:

let fetchURL = 'http://192.168.22.124:3000/source/';
  let image = name.map((picName) => {
    return picName
  })

  fetch(fetchURL + image)
  .then(response => response.json())
  .then(images => console.log(fetchURL + images));

Nodejs:

app.get('/source/:fileid', (req, res) => {
const { fileid } = req.params;
res.sendFile(__dirname + /data/ + fileid); 
});

Is there any better way to do than what I am doing above?

Q2) Also, how can I assign a value to an empty variable (which lives outside the fetch function)
jpg = fetchURL + images; So I can access it somewhere.

The response from the server is a binary file, not JSON formatted text. You need to read the response stream as a Blob.

const imageUrl = "https://.../image.jpg";

fetch(imageUrl)
  //                         vvvv
  .then(response => response.blob())
  .then(imageBlob => {
      // Then create a local URL for that image and print it 
      const imageObjectURL = URL.createObjectURL(imageBlob);
      console.log(imageObjectURL);
  });

Equivalent to solution by @maxpaj, but using async and await.

async function load_pic() {
    
        const url = '<REPLACE-WITH-URL>'
    
        const options = {
            method: "GET"
        }
    
        let response = await fetch(url, options)
    
        if (response.status === 200) {
            
            const imageBlob = await response.blob()
            const imageObjectURL = URL.createObjectURL(imageBlob);
    
            const image = document.createElement('img')
            image.src = imageObjectURL
    
            const container = document.getElementById("your-container")
            container.append(image)
        }
        else {
            console.log("HTTP-Error: " + response.status)
        }
    }

This question is 4 years old and I think in 2022 there are many ways to solve this. This is ES6 version using async calls.

First, I don't know if you are trying to download the image or insert the image into a img tag. So I will assume we want to download the image.

The process is simple: a) fetch the image as a blob ; b) convert blob to Base64 using URL.createObjectURL(blob) ; and c) trigger the download using a ghost a tag.

 const $btn = document.getElementById('downloadImage') const url = 'https://s3-ap-southeast-1.amazonaws.com/tksproduction/bmtimages/pY3BnhPQYpTxasKfx.jpeg' const fetchImage = async url => { const response = await fetch(url) const blob = await response.blob() return blob } const downloadImage = async url => { const imageBlob = await fetchImage(url) const imageBase64 = URL.createObjectURL(imageBlob) console.log({imageBase64}) const a = document.createElement('a') a.style.setProperty('display', 'none') document.body.appendChild(a) a.download = url.replace(/^.*[\\\/]/, '') a.href = imageBase64 a.click() a.remove() } $btn.onclick = event => downloadImage(url)
 <button id="downloadImage">Download Image</button>

Note:

StackOverflow uses a sandboxed iframe 's so we can test the download but you can use my codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM