Explain Codes LogoExplain Codes Logo

Download data URL file

javascript
blob-conversion
fetch-api
cross-browser-support
Alex KataevbyAlex Kataev·Feb 6, 2025
TLDR

Straight to the point - download a file from a data URL using this streamlined JavaScript function:

function downloadFile(dataURL, fileName) { const link = document.createElement('a'); link.href = dataURL; link.download = fileName; document.body.appendChild(link); // Firefox needs this, don't ask why 😃 link.click(); document.body.removeChild(link); // We love clean DOM, don't we? } // Invoke as downloadFile('data:text/plain;base64,aGVsbG8=', 'hello.txt');

Call downloadFile() passing in the data URL and the file name you prefer. This function creates an anchor (<a>) tag on-the-fly, sets href to the data URL, download to the file name, and triggers a click to start the download.

Download controls in depth

Blob conversion for complex file types

Working with non-image files, particularly in Chrome, we prefer converting to a blob. This method sidesteps security restrictions linked with direct data URL usage.

function downloadBlob(data, fileName, mimeType) { const blob = new Blob([data], { type: mimeType }); const url = window.URL.createObjectURL(blob); downloadFile(url, fileName); // Reusing our core function, reuse is key! setTimeout(() => window.URL.revokeObjectURL(url), 1000); // House cleaning! } // Invoke as downloadBlob('Hello, world!', 'hello.txt', 'text/plain');

Handling fetch errors

Error handling is essential when downloading files. Here's how to incorporate this using the fetch method:

fetch('path/to/file') .then(response => response.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); downloadFile(url, 'downloadedFile.ext'); // Gotcha! URL.revokeObjectURL(url); // Keep things tidy }) .catch(error => console.error('Download error:', error)); // Always be prepared!

Cross-browser strategies

Cross-browser support can be achieved efficiently with third-party libraries like download.js.

Advanced aspects and cheat-sheets

Libraries to the rescue

Libraries like downloadify serve as saviors for complex download scenarios and cross-browser compatibility, handling limitations of older browsers with grace.

User-centric downloads and archive management

Drag-and-drop functionalities combined with JavaScript-based archive management improves the file handling experience dramatically. Your application will be able to manipulate file archives without heavy backend logic!