【问题标题】:ReactJS: Unable to render image in UI from REST API responseReactJS:无法通过 REST API 响应在 UI 中呈现图像
【发布时间】:2018-01-03 03:21:13
【问题描述】:

我已经构建了一个返回图像的 REST API,并且我成功地通过 PostMan 代理获得了它的响应。 在我的 React 代码中,我有这个:

return fetch(url, sInit)
  .then((response) => {
    let blb = new Blob([response.body], { type: 'image/jpeg' });
    let fileUrl = (window.URL || window.webkitURL).createObjectURL(blb);
    window.open(fileUrl);
  })

生成的 blob url 没有图片。我错过了什么?

【问题讨论】:

    标签: image rest reactjs blob


    【解决方案1】:

    您可能希望使用fetch 的内置blob() 方法:

    fetch(
      'https://images.unsplash.com/35/SRkdurVYQFSFkMyHVwSu_spinnenweb-9536.jpg?dpr=2&auto=compress,format&fit=crop&w=376&h=251&q=80&cs=tinysrgb&crop='
    )
      .then(res => res.blob())
      .then(blob => {
        let fileUrl = (window.URL || window.webkitURL).createObjectURL(blob);
    
        const img = document.createElement('img');
        img.src = fileUrl;
        document.querySelector('body').appendChild(img);
      });

    【讨论】:

    • 您的回答很有帮助,但这在 IE 8 到 11 中不起作用。
    • 您是否添加了fetch polyfillfetch 在这些浏览器中是 not supported
    • 请查看文档,IE10及以上版本支持fetch,但任何版本的Internet Explorer都不支持blob()
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多