How to download a file in JavaScript

Programmatically downloading files in JavaScript enables dynamic file generation and download functionality without server-side processing. As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve implemented file downloads in numerous dashboard applications for data export features. The most reliable approach creates a temporary anchor element with a blob URL and programmatically triggers a click event. This method works across all modern browsers and supports various file types including text, CSV, and binary data.

Create a blob URL and use a temporary anchor element to trigger file downloads programmatically.

function downloadFile(data, filename, type = 'text/plain') {
    const blob = new Blob([data], { type })
    const url = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()

    document.body.removeChild(link)
    URL.revokeObjectURL(url)
}

// Usage
downloadFile('Hello, World!', 'greeting.txt')
downloadFile('name,age\nJohn,30', 'data.csv', 'text/csv')

This code creates a Blob object from the data, generates a temporary URL using createObjectURL, and creates an anchor element with the download attribute. The programmatic click triggers the browser’s download mechanism. Finally, it cleans up by removing the temporary elements and revoking the object URL to free memory.

Best Practice Note:

This is the download mechanism we use in CoreUI data tables for CSV and Excel export functionality. Always call URL.revokeObjectURL() after downloads to prevent memory leaks from accumulated blob URLs.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author