简体   繁体   English

从 API 中获取图像

[英]Fetch image from API

Q1) In my reactjs application, I am trying to fetch an API from my backend Nodejs server. Q1)在我的 reactjs 应用程序中,我试图从我的后端 Nodejs 服务器获取一个 API。 The API responds with an image file on request. API 根据请求以图像文件进行响应。

I can access and see image file on http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg我可以在http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg上访问和查看图像文件

But in my reactjs client side I get this error on console log.但是在我的 reactjs 客户端中,我在控制台日志中收到了这个错误。

Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0未捕获(承诺)SyntaxError:JSON 中的意外令牌 position 0

Reactjs: 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) Q2)另外,我如何为一个空变量(位于获取函数之外)赋值
jpg = fetchURL + images; jpg = fetchURL + 图片; So I can access it somewhere.所以我可以在某个地方访问它。

The response from the server is a binary file, not JSON formatted text.来自服务器的响应是一个二进制文件,而不是 JSON 格式的文本。 You need to read the response stream as a Blob.您需要将响应流作为 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.相当于@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)
        }
    }

This question is 4 years old and I think in 2022 there are many ways to solve this.这个问题已有 4 年历史,我认为在 2022 年有很多方法可以解决这个问题。 This is ES6 version using async calls.这是使用异步调用的 ES6 版本。

First, I don't know if you are trying to download the image or insert the image into a img tag.首先,我不知道您是要下载图像还是要将图像插入img标签。 So I will assume we want to download the image.所以我假设我们要下载图像。

The process is simple: a) fetch the image as a blob ;过程很简单:a) 以blob形式获取图像; b) convert blob to Base64 using URL.createObjectURL(blob) ; b) 使用URL.createObjectURL(blob) ) 将 blob 转换为Base64 and c) trigger the download using a ghost a tag. 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>

Note:笔记:

StackOverflow uses a sandboxed iframe 's so we can test the download but you can use my codepen StackOverflow 使用沙盒iframe ,因此我们可以测试下载,但您可以使用我的代码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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