簡體   English   中英

從 API 中獲取圖像

[英]Fetch image from API

Q1)在我的 reactjs 應用程序中,我試圖從我的后端 Nodejs 服務器獲取一個 API。 API 根據請求以圖像文件進行響應。

我可以在http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg上訪問和查看圖像文件

但是在我的 reactjs 客戶端中,我在控制台日志中收到了這個錯誤。

未捕獲(承諾)SyntaxError:JSON 中的意外令牌 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));

節點:

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

有沒有比我上面做的更好的方法?

Q2)另外,我如何為一個空變量(位於獲取函數之外)賦值
jpg = fetchURL + 圖片; 所以我可以在某個地方訪問它。

來自服務器的響應是一個二進制文件,而不是 JSON 格式的文本。 您需要將響應流作為 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);
  });

相當於@maxpaj 的解決方案,但使用異步和等待。

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)
        }
    }

這個問題已有 4 年歷史,我認為在 2022 年有很多方法可以解決這個問題。 這是使用異步調用的 ES6 版本。

首先,我不知道您是要下載圖像還是要將圖像插入img標簽。 所以我假設我們要下載圖像。

過程很簡單:a) 以blob形式獲取圖像; b) 使用URL.createObjectURL(blob) ) 將 blob 轉換為Base64 c) 使用 ghost a標簽觸發下載。

 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>

筆記:

StackOverflow 使用沙盒iframe ,因此我們可以測試下載,但您可以使用我的代碼筆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM