Create a File from AJAX request data and download!

Creating a file based on user requested parameters and making it available for the user to download is a common task often used in several web applications. But to implement it in your application is not that straightforward as it seems.

Although there are several ways through which this functionality can be achieved but the approach discussed in this post is that we will get data from the server and write it into a file which will be downloaded automatically on the client machine.

fetch(url)
 .then((response) => response.text())
 .then(data => {
     var downloadLink = document.createElement('a');
     downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
     downloadLink.setAttribute('download', 'file-'+Date.now()+'.txt');

     downloadLink.style.display = 'none';
     document.body.appendChild(downloadLink);

     downloadLink.click();

     document.body.removeChild(downloadLink);
 })

The above snippet creates a hidden anchor tag and sets data in-line. Then a click event is fired which in turn downloads the file and the tag is removed henceforth.

This approach is good for small sized files as the file size support varies for different browsers. But for a small sized file, this approach works pretty well.

Happy Coding!!