如何在Angular 4及以上版本中将图片Data URL转换为Blob?
Hey there! Great question—let's break this down for you so you can get this working in your Angular 4+ app smoothly.
First, let's address the blob-util compatibility: this package is actually vanilla JavaScript (no AngularJS-specific dependencies), so it does work in Angular 4+. That said, since Angular uses TypeScript, you might need to handle type declarations. But if you want a lighter, native approach (no third-party packages), that's totally doable too. Here are both options:
blob-util in Angular 4+ - Install the package first:
npm install blob-util --save - For TypeScript support, install the type declarations (if available):
If types aren't available, you can either add a simple type declaration file or usenpm install @types/blob-util --save-dev// @ts-ignoreto bypass TypeScript checks temporarily. - Import and use it in your component:
import * as blobUtil from 'blob-util'; // Example usage with promises const yourDataUrl = 'data:image/png;base64,iVBORw0KGgo...'; blobUtil.dataUriToBlob(yourDataUrl).then(blob => { // Do something with your Blob (e.g., upload, display) console.log('Converted Blob:', blob); }); // Or use async/await for cleaner code async convertDataUrl(dataUrl: string): Promise<Blob> { return await blobUtil.dataUriToBlob(dataUrl); }
Modern browsers have all the APIs you need to convert a Data URL to a Blob without external libraries. This approach is lightweight, fast, and fully compatible with any Angular version (4+ up to the latest releases).
Here's a reusable function you can drop into your component:
convertDataUrlToBlob(dataUrl: string): Blob { // Split the Data URL into its metadata and base64 data parts const [header, base64Data] = dataUrl.split(','); // Extract the MIME type from the header const mimeMatch = header.match(/:(.*?);/); const mimeType = mimeMatch ? mimeMatch[1] : ''; // Decode the base64 string to raw bytes const byteString = atob(base64Data); const arrayBuffer = new ArrayBuffer(byteString.length); const uint8Array = new Uint8Array(arrayBuffer); // Populate the Uint8Array with byte values for (let i = 0; i < byteString.length; i++) { uint8Array[i] = byteString.charCodeAt(i); } // Create and return the Blob return new Blob([arrayBuffer], { type: mimeType }); }
- Use it like this:
const yourDataUrl = 'data:image/png;base64,iVBORw0KGgo...'; const blob = this.convertDataUrlToBlob(yourDataUrl); console.log('Native-converted Blob:', blob);
Quick note
If you're targeting older browsers (like IE11), the native approach might need a polyfill for atob or Blob, but for modern browsers (which most Angular apps target now), this works flawlessly.
内容的提问来源于stack exchange,提问作者chaitra

