Home  >  Article  >  Web Front-end  >  Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?

Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 08:22:30519browse

 Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?

Obtaining a Blob from a DataURL

In certain scenarios, there is a need to transform arbitrary data into a Data URL using FileReader's readAsDataURL() method. However, can this Data URL be converted back into a Blob instance utilizing built-in browser APIs?

A solution has been proposed by a user named Matt:

Code Snippet:

<code class="js">function dataURItoBlob(dataURI) {
  // Convert base64 to raw binary data
  var byteString = atob(dataURI.split(',')[1]);

  // Extract the MIME component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  // Create an ArrayBuffer and Uint8Array
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);

  // Set the bytes of the buffer
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  // Create a Blob instance
  var blob = new Blob([ab], { type: mimeString });
  return blob;
}</code>

Note:

As mentioned in subsequent comments, BlobBuilder has become deprecated. Therefore, the code provided above is an updated version.

The above is the detailed content of Can You Convert a Data URL Back to a Blob in JavaScript Using Built-in APIs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn