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.

In-Memory

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.

<html>

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

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

</html>

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');
		  
      document.body.appendChild(downloadLink);
		}
		
		downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
		downloadLink.href = URL.createObjectURL(data);
		
		downloadLink.style.display = 'none';
		downloadLink.click();
}

Code

Plunkr