繁体   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