如何获取和显示 blob 图像

e.i*_*luf 8 javascript blob reactjs

我正在尝试将图像保存到 indexeddb,然后在 React 应用程序中获取并显示它们。我的方法是将图像转换为 blob 并将 blob url 保存到 indexeddb,然后在需要显示时获取 blob url 并将图像 url 设置为 .src。

我是如何创建 blob 的

fetch(imgurl, {
                mode: 'no-cors',
                method: "get",
                headers: {
                     "Content-Type": "application/json"
                } 
             }) 
            .then(response => response.blob())
            .then(async images => {
               
                    var blob_url = URL.createObjectURL(images)
                  
                    var blobA = blob_url.replace("blob:","") 
                    var blobB = blobA.replace('"','')
Run Code Online (Sandbox Code Playgroud)

这是 bloburl blob:http://localhost:3000/d7a55f39-b496-476b-8c3c-857874bd107c

然后,我删除 blob: 并将此网址保存在 indexeddb 中,以便在需要时获取 http://localhost:3000/d7a55f39-b496-476b-8c3c-857874bd107c

这是我需要使用 blob 图像的地方

import React from "react";
import { Row, Col, Container, Image } from 'react-bootstrap';

   
function Item({ item }) { 
    const imgurl = item.productimg
    fetch(imgurl)
        .then(res => res.blob()) // Gets the response and returns it as a blob
        .then(async blob => {
            const test = await blobToImage(blob)  
            console.log("image test",test)
        
            let objectURL = URL.createObjectURL(blob);
           let myImage = document.getElementById('myImg')
           myImage.src = objectURL;
            
        });
       
    return (
        <div className="item" id={item.id}>


            <Row>
                <Col> 
                <Image  id="myImg" width="50" height="58" rounded />

                </Col>
                <Col xs={6}>
                    <div className="item-info">
                        <p>{item.name}</p>
                    </div>
                </Col>
                <Col>3 of 3</Col>
            </Row>
           

            <div className="item-actions">
                <button className="btn-remove">X</button>
            </div>
        </div>
    );
}

export default Item;
Run Code Online (Sandbox Code Playgroud)

项目包含所有产品数据,包括保存的 blob url。问题是图像没有显示,我不明白为什么。

我可能做错了什么以及如何显示图像

Aka*_*ash 6

不要修改 的BlobURL。

当您blob:从 URL 字符串中取出该部分到 时Blob,浏览器不再知道您正在引用您的Blob. 相反,请尝试在使用 . 创建 URL 后单独保留该 URL URL.createObjectURL

最重要的是,当将组件与外部资源同步(例如获取数据)时,您应该使用React 的useEffecthook

反应示例

您可以在 StackBlitz 实时查看此示例

function Item({ item }) {
  const imgURL = item.productimg;
  const [blobURL, setBlobURL] = React.useState(null);

  React.useEffect(() => {
    const controller = new AbortController(); // https://developer.mozilla.org/en-US/docs/Web/API/AbortController
    const signal = controller.signal;
    fetch(imgURL, { signal })
      .then((res) => res.blob()) // Get the response and return it as a blob
      .then((blob) => { // Create a URL to the blob and use it without modifying it.
        setBlobURL(URL.createObjectURL(blob));
      })
      .catch((error) => { // Error handling here
        console.error(error);
      });

    // Cancel the fetch request on any dependency change
    return () => controller.abort();
  }, [imgURL]);

  return (
    <div className="item" id={item.id}>
      <Row>
        <Col>
          {blobURL ? <Image src={blobURL} id="myImg" width="50" height="58" rounded /> : <p>Loading...</p>}
        </Col>
        <Col xs={6}>
          <div className="item-info">
            <p>{item.name}</p>
          </div>
        </Col>
        <Col>3 of 3</Col>
      </Row>

      <div className="item-actions">
        <button className="btn-remove">X</button>
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

使用纯 JavaScript 的示例

const imgURL = "https://cdn62.picsart.com/182788826000202.jpg?type=webp&to=crop&r=256"
fetch(imgURL)
  .then(response => response.blob())
  .then(blob => {
    document.getElementById('my-img').src = URL.createObjectURL(blob)
  })
Run Code Online (Sandbox Code Playgroud)
<img id="my-img" />
Run Code Online (Sandbox Code Playgroud)

祝你好运...