Base64 File: React Download [hot]
For small files (typically under a few megabytes), you can embed the Base64 string directly into an tag's href attribute using a . javascript
Quick to implement and requires no external libraries. react download base64 file
const downloadBase64AsFile = (base64Data, fileName, contentType) => { const byteCharacters = atob(base64Data); // Decode Base64 const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: contentType }); // Create Blob const url = URL.createObjectURL(blob); // Generate temporary URL const link = document.createElement("a"); link.href = url; link.download = fileName; link.click(); URL.revokeObjectURL(url); // Clean up memory }; Use code with caution. Key Implementation Details How to convert base64 into Blob in React Native? For small files (typically under a few megabytes),
Limited by browser URL length restrictions and less memory-efficient for large files. Optimized Blob Conversion Method Direct Anchor Tag Method
const handleDownload = (base64String, fileName) => { // Ensure the string has the correct Data URI prefix const linkSource = `data:application/pdf;base64,${base64String}`; const downloadLink = document.createElement("a"); downloadLink.href = linkSource; downloadLink.download = fileName; downloadLink.click(); }; Use code with caution.
Downloading a Base64-encoded file is a frequent requirement in React applications, particularly when your backend returns a file as a string within a JSON response. You can implement this using a simple anchor tag for small files or a more robust conversion for larger assets. Direct Anchor Tag Method