How to Download Dynamic Files Using JavaScript

By

First of all we have to convert file data into a Blob object. Following example shows how to create a Blob containing plain text data. Most of the file generating libraries such as JSZip, PDFKit, html-to-image return this kind of Blob objects. Most of the time we manually create Blob objects for creating text/plain items. Then we can create an object url from the blob using URL.createObjectURL method. This creates a temporary URL with blob:// pseudo protocol. This URL is available until you close the browser tab or revoke it manually.

// source text content
const data = "Hello World"

// create a blob with data and mime type
const blob = new Blob([data], { type: "text/plain" })

// create a temporary object URL
const url = URL.createObjectURL(blob)

Let's create an anchor element and provide the required attributes. download attribute is the most important one, so instead of navigating to the assigned URL while clicking on the anchor, it will be forced to download as a file.

// create an anchor element
const anchor = document.createElement("a")

// set Blob URL as anchor href
anchor.href = url

// set download attribute
anchor.download = "MyFile.txt"

// hide element using style
anchor.style.display = "none"

// append into body element
document.body.appendChild(anchor)

// simulate click
anchor.click()

// remove anchor element from body
anchor.remove()

// revoke blob URL after sometime
setTimeout(() => URL.revokeObjectURL(url), 50)