Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use `URL.createObjectURL(blob)` instead of `image.src`?

Q1. In the context of asynchronous JavaScript and the need to ‘fetch’ data from the client-side, why can’t we just edit our image elements by its attribute src?

Q2. Why is the Blob conversion process necessary to go through?

Q3. What is the blob role?

e.g. Retrieving image file from JSON. (BTW, I extracted it from MDN webpage, mind the comments)


  function fetchBlob(product) {
    // construct the URL path to the image file from the product.image property
    let url = 'images/' + product.image;
    // Use fetch to fetch the image, and convert the resulting response to a blob
    // Again, if any errors occur we report them in the console.
    fetch(url).then(function(response) {
        return response.blob();
    }).then(function(blob) {
      // Convert the blob to an object URL — this is basically an temporary internal URL
      // that points to an object stored inside the browser
      let objectURL = URL.createObjectURL(blob);
      // invoke showProduct
      showProduct(objectURL, product);
    });
  }

like image 289
hyfyline Avatar asked Mar 02 '23 13:03

hyfyline


1 Answers

If you can, then use the url directly as the srcof your <img>.

Using a blob: URL is only useful if you have a Blob holding the image file, and you need to display it.

One common case where this happens is when you allow your users to pick a file from their disk. The file picker will give you access to a File object, which is a Blob, and which you can load in memory. However, you don't have access to an URI that points to the file on disk, so you can't set the src in that case.
Here you need to create a blob: URI which will point to the File object. The browser internal fetching mechanism will be able to retrieve the data on user's disk from this URL and thus to display that image:

document.querySelector('input').onchange = e => {
  const file = e.target.files[0]; // this Object holds a reference to the file on disk
  const url = URL.createObjectURL(file); // this points to the File object we just created
  document.querySelector('img').src = url;
};
<input type="file" accepts="image/*">
<img>

Other cases imply that you did create the image file from the front-end (e.g using a canvas).

But if your Blob is only the result of fetching the resource from your server, and that your server doesn't require a special request to serve it, then indeed, there is no real point...

like image 89
Kaiido Avatar answered Mar 13 '23 03:03

Kaiido