The detailed steps are as follows
1. Analyze Base64 data:
If the data stream contains the prefix data:…;base64,, first separate the MIME type and Base64 data part.
If there is no prefix, assume the default MIME type (such as application/octet-stream).
2. Base64 decoding:
Use atob to decode the Base64 string into a binary string.
Convert the binary string to Uint8Array.
3. Generate Blob:
Create binary data as a Blob object, specifying a type (such as text/plain).
4. Trigger download:
Use Temporary URL to create a Blob object.
Dynamically create an element, set its href attribute to a temporary URL, specify the file name, and trigger the click event to download.
5. Clean up temporary resources:
After the download is complete, remove the element and release the temporary URL.
The implementation code is as follows:
function downloadBase64Data(base64Data, fileName) { try { // Check whether Base64 data contains prefixes (such as data:...;base64,) let mimeType = ''; let base64String = ''; if ((',')) { const [metadata, data] = (','); mimeType = (/:(.*?);/)[1]; // Extract MIME type base64String = data; // Only the Base64 data part is taken } else { // If there is no prefix, the default is to some MIME type, such as application/octet-stream mimeType = 'application/octet-stream'; base64String = base64Data; } // Base64 decoding const binaryString = atob(base64String); // Decode Base64 const binaryData = new Uint8Array(); for (let i = 0; i < ; i++) { binaryData[i] = (i); } // Create a Blob object const blob = new Blob([binaryData], { type: mimeType }); // Create temporary URLs using Blobs const url = (blob); // Create <a> element and trigger download const a = ('a'); = url; = fileName; (a); // It must be added to the DOM (); // Clean up (a); (url); ('File download successfully'); } catch (error) { ('Download failed:', ); } } // Example usageconst base64Data = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=='; // Example Base64 dataconst fileName = ''; downloadBase64Data(base64Data, fileName);
Advantages
No API dependencies: suitable for direct processing of pure Base64 data streams.
High compatibility: supports modern browsers (Chrome, Firefox, Edge).
Things to note
Filename: Make sure fileName is a user-friendly filename and contains an extension.
Performance issues: For larger Base64 data, the memory usage will be higher.
Security: Ensure Base64 data is trustworthy and avoid processing malicious input.
This is the article about JavaScript downloading base64 data and compatible with low versions. For more related JavaScript downloading base64 data content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!