If the data is generated on the client-side (like a JSON string or text), you must first wrap it in a (Binary Large Object) and generate a temporary Object URL . Steps for implementation: Create a Blob: Define the content and MIME type.
async function downloadFromAPI(apiUrl, fileName) { try { const response = await fetch(apiUrl); const blob = await response.blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; a.click(); URL.revokeObjectURL(url); } catch (error) { console.error('Download failed:', error); } } Use code with caution. 4. Handling Base64 Encoded Strings How to download a base64-encoded image? - Stack Overflow download function in javascript
When a file is hosted on a server but requires specific handling (like authentication headers), you should use the Fetch API to retrieve the file as a blob before triggering the download. javascript If the data is generated on the client-side