Welcome folks today in this blog post we will be downloading csv file
as an attachment using blob
from dynamic data
present inside the textarea in the browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <textarea name="" id="data" cols="30" rows="10"></textarea> <button onclick="downloadCSV()">Download CSV File</button> </body> <script> function downloadCSV() { let data = ` Name,Age,Country Kane,25,New Zealand, Devon,24,New Zealand, Tom,25,New Zealand, Tim,27,New Zealand ` const blob = new Blob([document.getElementById('data').value], { type: 'octet-stream' }) const href = URL.createObjectURL(blob) const a = Object.assign(document.createElement('a'), { href: href, style: 'display:none', download: 'data.csv' }) document.body.appendChild(a) a.click() URL.revokeObjectURL(href) a.remove() } </script> </html> |
As you can see in the above html
code we have the textarea
where we allow the users
to enter the csv
and then we have the button to download the csv
file as an attachment using the blob
as shown below.