Downloading String Data as a File

By Shaun A Noordin

by alexbfree

HTML

<!DOCTYPE html>
<body>
  <a href="#" id="download" download="test.csv">Download CSV!</a>
</body>

JavaScript

var data = "name,colour\nApple,red\nBanana,yellow\nCherry,red"
      var dataBlob = new Blob([data], {type: 'text/csv'});
      var dataAsAFile = window.URL.createObjectURL(dataBlob);
      
      //CHOOSE YOUR OWN ADVENTURE!
      
      //OPTION 1: Prompt the user to download the file
      //--------------------------------
      //This works well if you're using type: 'text/csv'
      //But, if you use 'text/plain', then on FF & Chrome it just opens a new
      //page with the text content instead of prompting a download dialog.
      
      //  window.open(dataAsAFile);
      //  window.URL.revokeObjectURL(dataAsAFile);  //Cleanup
      //--------------------------------
      
      //OPTION 2: Create a clickable <a>
      //--------------------------------
      //This is the easy way of creating a download link, but oh man, I got
      //such weird errors when trying to get React to react to a
      //download="test.csv" attribute.
      
      document.getElementById("download").href = dataAsAFile;
      
      //Remember to call window.URL.revokeObjectURL(dataAsAFile) when the user
      //is finished using the <a>.
      //--------------------------------