Generating and Downloading files client-side with Javascript
In this article, we are going to take a look at how to generate and download files right in the user's browser without making a request to the server. Sometimes, in web applications, users may generate content that they want to keep for offline use. Rather than sending a request to the server to generate a file from the content and serve it to the user, it is possible to achieve this with client-side javascript.
So, to illustrate, let's say we have the following markup :
<html>
<body>
<form onsubmit='initDownload()' method="" action=''>
<textarea id='user-content'> Welcome</textarea>
<button type='submit'> Download </button>
</form>
</body>
</html>
The user enters some information in the text box provided and then clicks on the download button which will initiate the download.
Now let's explore the initDownlaod
function.
<script>
function initDownload(ev){
ev.preventDefault()
let content = document.querySelector('#user-content').value
let url = generateFileURL(content)
downloadFile(url)
}
...
</script>
As soon as the submit event
is triggered, it calls the initDownload
function which starts by preventing the default behaivour using the event.preventDefault()
function which could have been to submit it to the url specified in the form action
. The second line inside the function gets the content that the user enters into the textbox and invokes the generateFileURL function with it as an argument.
function generateFileURL(content){
let fileBlob = new Blob([content], {type:'text/plain'})
return URL.createObjectURL(fileBlob)
}
This function does two things. Firstly, it creates a new blob object using the Blob API constructor by wrapping the content in an aray (more info about blob can be found here). This blob object is then used to generate a URL which will later be used to download the file. The function returns this url.
function downloadFIle(url) {
let linkTag = document.createElement('a')
linkTag.setAttribute('download', newFile) // filename
linkTag.setAttribute('href', url)
document.body.appendChild(linkTag)
linkTag.style.display = 'none'
linkTag.click()
URL.revokeObjectURL(url)
document.body.removeChild(linkTag)
}
This function does the actual download and a little cleanup. The function generates an a
element (anchor element) and modifies its download
attribute to the name of the file to be downloaded and the href
attribute to the url created in the previous function. After that, it appends this element to the body of the document and simulates a click event on it. It finally destroys the url and remove the anchor element from the DOM after the user might have downloaded the file.
This is just a very basic example of downloading files using client-side javascript. Thank you for reading.