The blob object is converted to a file file and displayed in img

Article directory

full code

<script>
  fetch(
    "https://desk-fd.zol-img.com.cn/t_s1440x900c5/g7/M00/0B/02/ChMkK2Plp3SIejdhADnMQEaMKKsAAMrvwBgm7cAOcxY127.jpg"
  )
    .then((response) => response.blob())
    .then((blob) => {
      
      
      // 将Blob转换为File
      const file = new File([blob], "icon.png", {
      
       type: "image/png" });

      // 创建图像元素并显示图像
      const imageUrl = URL.createObjectURL(file);
      const imgElement = document.createElement("img");
      imgElement.src = imageUrl;
      document.body.appendChild(imgElement);

      // 图像元素完成加载时,释放URL对象
      imgElement.addEventListener("load", () => {
      
      
        URL.revokeObjectURL(imageUrl);
        console.log("URL对象已释放!");
      });
    });
</script>

core code

Create a Blobobject, then convert it to Filean object and use it as the source for the image

// 通过fetch获取图像数据
fetch('./icon.png')
  .then(response => response.blob())
  .then(blob => {
    
    
    // 将Blob转换为File
    const file = new File([blob], 'icon.png', {
    
     type: 'image/png' });

    // 创建图像元素并显示图像
    const imageUrl = URL.createObjectURL(file);
    const imgElement = document.createElement('img');
    imgElement.src = imageUrl;
    document.body.appendChild(imgElement);
  });

This code will fetchtake the image data using a , Blobconvert to File, and then Fileconvert to a URL that is assigned to imgthe element's srcattribute to display the image. This code assumes the image file is in your project root and named icon.png. You need to replace the filename and type with the actual file you are using.

It's also worth noting that if you decide to put this code in a function, you don't need to use asyncthe / awaitor .then(), since fetchthe request itself returns a Promise object.

  • Error:

    Access to fetch at ‘file:///C:/Users/26502/Desktop/icon.png’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

  • Resolve (upload the image file to cloud storage or web server)

    This error is usually due to the browser's security policies. For security reasons, browsers do not allow direct access to files in the file system from the local computer.

    When debugging development on your local computer, you can try installing a plugin or extension in your browser that allows direct access to files in the file system from your local computer. For example, Allow CORS: Access-Control-Allow-Originis a popular Chrome extension that also works on Firefox. You can probably fix this by installing the extension, enabling it, and reloading your page.

    Another solution is to upload your image files to cloud storage or a web server. This will allow you to access files from the network via the HTTP protocol, thus avoiding the restrictions of the browser's local security policy.

Replenish

If you URL.createObjectURL()created a URL object using , you should manually release the object when it is no longer needed, to free memory and avoid the risk of browser memory leaks.

You can call just before the image element is removed from the DOM URL.revokeObjectURL(). URL.revokeObjectURL()For example, you could add an event listener that is called when an image element finishes loading :

const imageUrl = URL.createObjectURL(file);
const imgElement = document.createElement('img');
imgElement.src = imageUrl;
document.body.appendChild(imgElement);

// 图像元素完成加载时,释放URL对象
imgElement.addEventListener('load', () => {
    
    
  URL.revokeObjectURL(imageUrl);
  console.log('URL对象已释放!')
});

This code will create a <img>element, assign it a URL, and add the element to the body. It then adds an loadevent listener that releases the URL object when the image has finished loading.

Also, be aware that in some cases the browser may loadrelease the URL object immediately before the event, so when assigning imgthe element to srcthe attribute, you should do this as quickly as possible so that it fires immediately before the URL is memorized loadevent.

Finally, it's important to note that you don't need to manually free the URL object when FileReaderyou read from the object File. Since FileReaderthe file is actually just read into memory, no URL object is generated.

fetch

Fetchis a modern web API for providing asynchronous requests and responses to resources in web applications. It provides a simple, flexible, and readable approach that is more scalable and functional than the AJAX-style XHR.

Using fetch, you can easily fetch data from the server and process the response in a variety of formats. As with traditional XHR, you can specify various configuration options such as request method, headers, credentials, and more.

Here's an fetchexample of getting JSON data using :

fetch('https://example.com/api/data.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we use fetchthe method to issue a GET request to request JSON data, then use .then()the parse JSON formatted data in the response, and log the parsed data to the console. If any errors occur, errors are caught and logged to the console.

In addition, you can also specify other request options, such as request method, request body, and request headers, as follows:

fetch('https://example.com/api/data', {
    
    
  method: 'POST',
  headers: {
    
    
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YourToken'
  },
  body: JSON.stringify({
    
    
    name: 'John Doe',
    email: '[email protected]'
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example, we use fetchthe method to make a POST request, the request header contains Content-Typeand Authorizationheaders, and the request body is a JSON object containing name and email. We then parse the JSON data in the response and log it to the console.

In summary, FetchAPI provides a flexible and simple way to handle asynchronous requests and responses for web applications, which is more readable and scalable than traditional XHR.

Guess you like

Origin blog.csdn.net/qq_51532249/article/details/131284292