By   April 13, 2017

Create In-Memory file & Downloading Data

In this post we are going to add ability to create an in-memory file and add ability to download it using a link and a button.


Here is an HTML file. Here we are adding a Link with download attribute set as Download2.csv. This would download the file as Download2.csv as user clicks the link. We have also added a button. Clicking the button would call ExportData() function, defined later.


    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>

    <h1>Create In-Memory file & Downloading Data</h1>
    <a id="aDownloadCsv" download="Download2.csv">Download Link</a>
    <button onclick="ExportData()">Download Button</button>


We have also call AssignDataToLink(), which should assign the code to the anchor tag to download the file. We have also added a script file reference script.js in the scripts section of the above HTML file.

We have defined AssignDataToLink() in script.js. It creates the data as comma separated values. We are also adding the data to href of the anchor tag.

function AssignDataToLink() {
  	var csv = "Id,Value\n1,Muhammad\n";
		var data = new Blob([csv]);
		var downloadLink = document.getElementById("aDownloadCsv");
		downloadLink.href = URL.createObjectURL(data);

Additionally, we are defining ExportData() function in script.js. It also creates some comma separated data, creates a link and add it to the DOM. We just call the click() for the anchor tag.

function ExportData() {
  	var csv = "Id, Value\n1,Muhammad\n";
		var data = new Blob([csv]);
		var downloadLink = document.getElementById("aDownloadCsv2");
		if (downloadLink == null) {
		  downloadLink = document.createElement('a');
		  downloadLink.setAttribute('download', 'DownloadedFile.csv');
		  downloadLink.setAttribute('id', 'aDownloadCsv2');
		downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
		downloadLink.href = URL.createObjectURL(data); = 'none';;